#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; }