Add another option for c heapsort, minor refactors, update docs
This commit is contained in:
@@ -1,8 +1,18 @@
|
||||
#include "../data_structures/heap.h"
|
||||
#include "sort_heap.h"
|
||||
|
||||
void dlos_sort_heap(dlos_Heap *h) {
|
||||
int original_size = h->size;
|
||||
void dlos_heapsort_array(dlos_ComparableNode *arr, int size, int (*compare)()) {
|
||||
dlos_Heap heap = { .size = size, .arr = arr, .arr_size = size, .compare = compare };
|
||||
dlos_max_heap(&heap);
|
||||
for (int i = heap.size - 1; i > 0; i--) {
|
||||
dlos_node_swap(heap.arr, 0, i);
|
||||
heap.size -= 1;
|
||||
dlos_sift_down(0, &heap);
|
||||
}
|
||||
}
|
||||
|
||||
// already have the heap, want to sort its array
|
||||
void dlos_heapsort_heap(dlos_Heap *h) {
|
||||
for (int i = h->size - 1; i > 0; i--) {
|
||||
dlos_node_swap(h->arr, 0, i);
|
||||
h->size -= 1;
|
||||
|
@@ -2,4 +2,37 @@
|
||||
|
||||
#include "../data_structures/heap.h"
|
||||
|
||||
void dlos_sort_heap(dlos_Heap *h);
|
||||
// // example use of dlos_heapsort_array
|
||||
// // define a comparison function for the nodes
|
||||
// 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[]) {
|
||||
// // have an array (could be malloc'd/heap memory or something in the stack)
|
||||
// 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];
|
||||
// }
|
||||
// // call sort with pointer to array, size, and pointer to the compare func
|
||||
// dlos_heapsort_array(a, test_size, compare_nodes);
|
||||
// for (int i = 0; i < test_size; i++) {
|
||||
// if (i == 0) printf("sorted: ");
|
||||
// printf("%d, ", *((int*) a[i].value));
|
||||
// if (i == test_size - 1) printf("\n");
|
||||
// }
|
||||
// return 0;
|
||||
// }
|
||||
|
||||
void dlos_heapsort_array(dlos_ComparableNode *arr, int size, int (*compare)());
|
||||
void dlos_heapsort_heap(dlos_Heap *h);
|
||||
|
Reference in New Issue
Block a user