Files
dlos/c/data_structures/heap.h

49 lines
1.4 KiB
C

#pragma once
typedef struct dlos_ComparableNode {
void *value;
} dlos_ComparableNode;
typedef struct dlos_Heap {
int size;
dlos_ComparableNode *arr;
int (*compare)(dlos_ComparableNode *a, dlos_ComparableNode *b);
} dlos_Heap;
void dlos_node_swap(dlos_ComparableNode *arr, int a, int b);
void dlos_sift_down(int i, dlos_Heap *h);
void dlos_max_heap(dlos_Heap *h);
// example of how the heap can be used
// here, each node value points to a plain int, but can substitute with other types
//
// int compare_nodes(dlos_ComparableNode *a, dlos_ComparableNode *b) {
// int left = *((int*) a->value);
// int right = *((int*) b->value);
// if (left > right) {
// return -1;
// } else if (left == right) {
// return 0;
// } else {
// return 1;
// }
// }
//
// int main(int argc, char *argv[]) {
// int test_size = 10;
// int data_storage[] = {73, 6, 57, 88, 60, 42, 83, 72, 48, 85};
// dlos_ComparableNode a[test_size];
// for (int i = 0; i < test_size; i++) {
// a[i].value = &data_storage[i];
// }
// dlos_Heap heap = { .size = test_size, .arr = a, .compare = compare_nodes };
// dlos_max_heap(&heap);
// dlos_sort_heap(&heap);
// for (int i = 0; i < test_size; i++) {
// if (i == 0) printf("sorted: ");
// printf("%d, ", *((int*) heap.arr[i].value));
// if (i == test_size - 1) printf("\n");
// }
// return 0;
// }