-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathheap.h
136 lines (105 loc) · 2.68 KB
/
heap.h
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#ifndef HEAP_H
#define HEAP_H
#include <stdbool.h>
#include <stdlib.h>
#include "helpers.h"
#include "sort.h"
void __heap_build(void *array, unsigned int count, unsigned int size, swap_t swp, compare_t cmp);
void __heap_push_up(void *array, unsigned int e, unsigned int count, unsigned int size, swap_t swp, compare_t cmp);
void __heap_push_down(void *array, unsigned int e, unsigned int count, unsigned int size, swap_t swp, compare_t cmp);
struct heap {
unsigned int size;
unsigned int max;
assign_t assign;
swap_t swp;
compare_t cmp;
unsigned int nsize;
void *nodes;
};
static inline bool heap_init(struct heap *heap, unsigned int max,
unsigned int size,
assign_t assign,
swap_t swp,
compare_t cmp)
{
heap->nodes = malloc(size*max);
if (!heap->nodes)
return false;
heap->size = 0;
heap->max = max;
heap->swp = swp;
heap->assign = assign;
heap->cmp = cmp;
heap->nsize = size;
return true;
}
static inline void heap_destroy(struct heap *heap)
{
free(heap->nodes);
}
static inline bool
heap_push(struct heap *heap, void *data)
{
char *nodes = heap->nodes;
typeof(heap->size) size = heap->size;
typeof(heap->nsize) nsize = heap->nsize;
if (size == heap->max)
return false;
heap->assign(&nodes[size*nsize], data);
++size;
__heap_push_up(nodes, size-1, size,
heap->nsize, heap->swp, heap->cmp);
heap->size = size;
return true;
}
static inline void *
heap_get_top(struct heap *heap)
{
if (0 == heap->size)
return NULL;
return heap->nodes;
}
static inline bool
heap_pop_top(struct heap *heap, void *data)
{
char *nodes = heap->nodes;
typeof(heap->size) size = heap->size;
typeof(heap->nsize) nsize = heap->nsize;
if (0 == size)
return false;
if (data)
heap->assign(data, nodes);
--size;
if (size) {
heap->assign(nodes, &nodes[size*nsize]);
__heap_push_down(nodes, 0, size,
heap->nsize, heap->swp, heap->cmp);
}
heap->size = size;
return true;
}
static inline void *
heap_get_bottom(struct heap *heap)
{
char *nodes = heap->nodes;
typeof(heap->size) size = heap->size;
typeof(heap->nsize) nsize = heap->nsize;
if (0 == size)
return NULL;
return &nodes[(size-1)*nsize];
}
static inline bool
heap_pop_bottom(struct heap *heap, void *data)
{
char *nodes = heap->nodes;
typeof(heap->size) size = heap->size;
typeof(heap->nsize) nsize = heap->nsize;
if (0 == size)
return false;
--size;
if (data)
heap->assign(data, &nodes[size*nsize]);
heap->size = size;
return true;
}
#endif