36 #define HEAP_PRINT_LEVEL_PADDING 4
40 int (*compare)(
const void *key1,
const void *key2);
41 void (*destroy)(
void *data);
46 static void print_tree(
Heap hp,
int ele_idx,
int level,
void (*callback)(
const void *data));
47 static int HEAPparent(
int npos);
48 static int HEAPleft(
int npos);
49 static int HEAPright(
int npos);
54 Heap HEAPinit(
int (*compare)(
const void *key1,
const void* key2),
void (*destroy)(
void *data))
58 if ((hp = (
Heap)malloc(
sizeof(
struct Heap_)))==NULL)
62 hp->compare = compare;
63 hp->destroy = destroy;
74 if (hp->destroy != NULL)
77 hp->destroy(hp->tree[i]);
88 int currpos, parentpos;
91 if ((tmp = realloc(hp->tree, (
HEAPsize(hp) + 1) *
sizeof(
void *))) == NULL)
94 hp->tree = (
void **)tmp;
97 hp->tree[
HEAPsize(hp)] = (
void *)data;
101 parentpos = HEAPparent(currpos);
103 while (currpos > 0 && hp->compare(hp->tree[parentpos], hp->tree[currpos]) < 0)
106 tmp = hp->tree[parentpos];
107 hp->tree[parentpos] = hp->tree[currpos];
108 hp->tree[currpos] = tmp;
112 parentpos = HEAPparent(currpos);
124 return hp->size ? hp->tree[0] : NULL;
131 int currpos, leftpos, rightpos, tmppos;
146 if ((temp = (
void **)realloc(hp->tree, (
HEAPsize(hp) - 1) *
sizeof(
void *))) == NULL)
176 leftpos = HEAPleft(currpos);
177 rightpos = HEAPright(currpos);
179 if (leftpos <
HEAPsize(hp) && hp->compare(hp->tree[leftpos], hp->tree[currpos]) > 0)
184 if (rightpos <
HEAPsize(hp) && hp->compare(hp->tree[rightpos], hp->tree[tmppos]) > 0)
188 if (tmppos == currpos)
196 temp = hp->tree[tmppos];
197 hp->tree[tmppos] = hp->tree[currpos];
198 hp->tree[currpos] = temp;
224 for (i = 0; i < hp->size; ++i)
225 callback(hp->tree[i]);
229 print_tree(hp, 0, 0, callback);
235 static void print_tree(
Heap hp,
int ele_idx,
int level,
void (*callback)(
const void *data))
240 if (ele_idx >= hp->size)
249 callback(hp->tree[ele_idx]);
254 print_tree(hp, HEAPleft(ele_idx), level+1, callback);
255 print_tree(hp, HEAPright(ele_idx), level+1, callback);
259 static int HEAPparent(
int npos)
265 static int HEAPleft(
int npos)
271 static int HEAPright(
int npos)