forked from beanstalkd/beanstalkd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.c
138 lines (107 loc) · 2.52 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
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
137
138
/* Copyright (C) 2007 Keith Rarick and Philotic Inc.
* Copyright 2011 Keith Rarick
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "t.h"
#include <stdlib.h>
#include <sys/time.h>
#include <stdio.h>
#include <string.h>
#include <event.h>
#include "dat.h"
static void
set(Heap *h, int k, void *x)
{
h->data[k] = x;
h->rec(x, k);
}
static void
swap(Heap *h, int a, int b)
{
void *tmp;
tmp = h->data[a];
set(h, a, h->data[b]);
set(h, b, tmp);
}
static int
cmp(Heap *h, int a, int b)
{
return h->cmp(h->data[a], h->data[b]);
}
static void
siftdown(Heap *h, int k)
{
for (;;) {
int p = (k-1) / 2; /* parent */
if (k == 0 || cmp(h, k, p) >= 0) {
return;
}
swap(h, k, p);
k = p;
}
}
static void
siftup(Heap *h, int k)
{
for (;;) {
int l, r, s;
l = k*2 + 1; /* left child */
r = k*2 + 2; /* right child */
/* find the smallest of the three */
s = k;
if (l < h->len && cmp(h, l, s) < 0) s = l;
if (r < h->len && cmp(h, r, s) < 0) s = r;
if (s == k) {
return; /* satisfies the heap property */
}
swap(h, k, s);
k = s;
}
}
int
heapinsert(Heap *h, void *x)
{
int k;
if (h->len == h->cap) {
void **ndata;
int ncap = (h->len+1) * 2; /* allocate twice what we need */
ndata = malloc(sizeof(void*) * ncap);
if (!ndata) {
return 0;
}
if (h->data) {
memcpy(ndata, h->data, sizeof(void*)*h->len);
free(h->data);
}
h->data = ndata;
h->cap = ncap;
}
k = h->len;
h->len++;
set(h, k, x);
siftdown(h, k);
return 1;
}
void *
heapremove(Heap *h, int k)
{
void *x;
if (k >= h->len) {
return 0;
}
x = h->data[k];
h->len--;
set(h, k, h->data[h->len]);
siftdown(h, k);
siftup(h, k);
return x;
}