-
Notifications
You must be signed in to change notification settings - Fork 3
/
heap.c
79 lines (72 loc) · 1.81 KB
/
heap.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <assert.h>
#include "heap.h"
/* With a one based binary heap parent is at i/2 and children are at
2i, 2i+1. */
void heap_insert_min(Heap heap, Token key, float value) {
uint32_t n = ++heap_size(heap);
while (n > 1) {
uint32_t p = n >> 1;
if (heap[p].logp <= value) break; /* */
heap[n] = heap[p];
n = p;
}
heap[n].token = key;
heap[n].logp = value;
}
void heap_insert_max(Heap heap, Token key, float value) {
uint32_t n = ++heap_size(heap);
while (n > 1) {
uint32_t p = n >> 1;
if (heap[p].logp >= value) break; /* */
heap[n] = heap[p];
n = p;
}
heap[n].token = key;
heap[n].logp = value;
}
Hpair heap_delete_min(Heap heap) {
assert(heap_size(heap) > 0);
Hpair top = heap[1];
Hpair bot = heap[heap_size(heap)];
uint32_t end = --heap_size(heap);
uint32_t p = 1;
uint32_t n;
while ((n = p << 1) <= end) {
if ((n < end) && (heap[n+1].logp <= heap[n].logp)) n++; /* */
if (bot.logp <= heap[n].logp) break; /* */
heap[p] = heap[n];
p = n;
}
heap[p] = bot;
return top;
}
Hpair heap_delete_max(Heap heap) {
assert(heap_size(heap) > 0);
Hpair top = heap[1];
Hpair bot = heap[heap_size(heap)];
uint32_t end = --heap_size(heap);
uint32_t p = 1;
uint32_t n;
while ((n = p << 1) <= end) {
if ((n < end) && (heap[n+1].logp >= heap[n].logp)) n++; /* */
if (bot.logp >= heap[n].logp) break; /* */
heap[p] = heap[n];
p = n;
}
heap[p] = bot;
return top;
}
void heap_sort_max(Heap heap) {
uint32_t size = heap_size(heap);
for (uint32_t i = size; i > 1; i--) {
heap[i] = heap_delete_min(heap);
}
heap_size(heap) = size;
}
void heap_sort_min(Heap heap) {
uint32_t size = heap_size(heap);
for (uint32_t i = size; i > 1; i--) {
heap[i] = heap_delete_max(heap);
}
heap_size(heap) = size;
}