From 8cfe7b7d69470f46eb411b8e94cf68c7279bddfd Mon Sep 17 00:00:00 2001 From: juan Date: Sat, 22 Oct 2022 15:04:56 +0800 Subject: [PATCH] Add 7-1 --- semester3/pset3/7-1-Binary-Heap.c | 108 ++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 semester3/pset3/7-1-Binary-Heap.c diff --git a/semester3/pset3/7-1-Binary-Heap.c b/semester3/pset3/7-1-Binary-Heap.c new file mode 100644 index 0000000..bd47f08 --- /dev/null +++ b/semester3/pset3/7-1-Binary-Heap.c @@ -0,0 +1,108 @@ +#include +#include + +typedef struct heap { + int* arr; + int capacity; + int size; +} heap; + +heap* newHeap(int size) { + heap* new = malloc(sizeof(heap)); + + new->arr = malloc(sizeof(int) * size); + + new->size = 0; + new->capacity = size; + + return new; +} + +void swap(int* l, int* r) { + int tmp = *r; + *r = *l; + *l = tmp; +} + +int max(int l, int r) { + return (l > r) ? l : r; +} + +int parent(int i) { + return (i - 1) / 2; +} + +int left (int i) { + return i * 2 + 1; +} + +int right (int i) { + return i * 2 + 2; +} + +void insert(heap* h, int val) { + int i = h->size++; + + h->arr[i] = val; + + while (i != 0 && h->arr[i] < h->arr[parent(i)]) { + swap(&h->arr[i], &h->arr[parent(i)]); + i = parent(i); + } +} + +void heapify(heap * h, int i) { + int smallest = i; + int l = left(i); + int r = right(i); + + // comparing size is important! + if (l < h->size && h->arr[smallest] > h->arr[l]) { + smallest = l; + } + if (r < h->size && h->arr[smallest] > h->arr[r]) { + smallest = r; + } + + if (smallest != i) { + swap(&h->arr[smallest], &h->arr[i]); + heapify(h, smallest); + } +} + +void buildHeap(heap* h) { + int start = h->size / 2 - 1; + + while (start >= 0) { + heapify(h, start--); + } +} + +void print(int* array, int size) { + for (int i = 0; i < size - 1; i++) { + printf("%d,", array[i]); + } + printf("%d\n", array[size - 1]); +} + +int main(void) { + int size; + scanf("%d", &size); + + int tmp; + heap* h1 = newHeap(size); + heap* h2 = newHeap(size); + h2->size = size; + + for (int i = 0; i < size; i++) { + scanf("%d,", &tmp); + h2->arr[i] = tmp; + insert(h1, tmp); + } + + buildHeap(h2); + print(h1->arr, size); + print(h2->arr, size); + + return 0; +}