-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap_sort.c
34 lines (30 loc) · 945 Bytes
/
heap_sort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "includes.h"
static void heapify(void* array[], size_t index, size_t max, int (*cmp)(void*, void*)) {
size_t largest = index;
size_t left = 2 * index + 1;
size_t right = 2 * index + 2;
if (left < max && (*cmp)(array[left], array[index]) > 0) {
largest = left;
}
if (right < max && (*cmp)(array[right], array[largest]) > 0) {
largest = right;
}
if (largest != index) {
swap(&array[largest], &array[index]);
heapify(array, largest, max, cmp);
}
}
static void build_heap(void* array[], size_t size, int (*cmp)(void*, void*)) {
size_t i;
for (i = (size / 2) - 1; i >= 0; i--) {
heapify(array, i, size, cmp);
}
}
void heap_sort(void* array[], size_t size, int (*cmp)(void*, void*)) {
size_t i;
build_heap(array, size, cmp);
for (i = size - 1; i >= 1; i--) {
swap(&array[0], &array[i]);
heapify(array, 0, i, cmp);
}
}