BUPT-homework/semester3/pset3/7-1-Binary-Heap.c

102 lines
1.7 KiB
C
Raw Normal View History

2022-10-22 15:04:56 +08:00
#include <stdio.h>
#include <stdlib.h>
typedef struct heap {
2022-10-25 19:43:48 +08:00
int *arr;
2022-10-22 15:04:56 +08:00
int capacity;
int size;
} heap;
2022-10-25 19:43:48 +08:00
heap *newHeap(int size) {
heap *new = malloc(sizeof(heap));
2022-10-22 15:04:56 +08:00
new->arr = malloc(sizeof(int) * size);
new->size = 0;
new->capacity = size;
return new;
}
2022-10-25 19:43:48 +08:00
void swap(int *l, int *r) {
2022-10-22 15:04:56 +08:00
int tmp = *r;
*r = *l;
*l = tmp;
}
2022-10-25 19:43:48 +08:00
int max(int l, int r) { return (l > r) ? l : r; }
2022-10-22 15:04:56 +08:00
2022-10-25 19:43:48 +08:00
int parent(int i) { return (i - 1) / 2; }
2022-10-22 15:04:56 +08:00
2022-10-25 19:43:48 +08:00
int left(int i) { return i * 2 + 1; }
2022-10-22 15:04:56 +08:00
2022-10-25 19:43:48 +08:00
int right(int i) { return i * 2 + 2; }
2022-10-22 15:04:56 +08:00
2022-10-25 19:43:48 +08:00
void insert(heap *h, int val) {
2022-10-22 15:04:56 +08:00
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);
}
}
2022-10-25 19:43:48 +08:00
void heapify(heap *h, int i) {
2022-10-22 15:04:56 +08:00
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);
}
}
2022-10-25 19:43:48 +08:00
void buildHeap(heap *h) {
2022-10-22 15:04:56 +08:00
int start = h->size / 2 - 1;
while (start >= 0) {
heapify(h, start--);
}
}
2022-10-25 19:43:48 +08:00
void print(int *array, int size) {
2022-10-22 15:04:56 +08:00
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;
2022-10-25 19:43:48 +08:00
heap *h1 = newHeap(size);
heap *h2 = newHeap(size);
// make sure this one.
2022-10-22 15:04:56 +08:00
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;
}