-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_heap.c
70 lines (61 loc) · 942 Bytes
/
binary_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
#include <stdio.h>
#include <string.h>
int heap[100];
int hs = 0;
void sink(int p)
{
int q = p << 1, a = heap[p];
while(q <= hs) {
if(q < hs && heap[q+1] < heap[q]) q++;
if(heap[q] >= a) break;
heap[p] = heap[q];
p = q;
q = p<<1;
}
heap[p] = a;
}
int deleteMin()
{
int r = heap[1];
heap[1] = heap[hs--];
sink(1);
return r;
}
void swim(int p)
{
int q = p >> 1, a = heap[p];
while(q && a < heap[q]) {
heap[p] = heap[q];
p = q;
q = p >> 1;
}
heap[p] = a;
}
void insert(int a)
{
heap[++hs] = a;
swim(hs);
}
void build()
{
for(int i = hs / 2; i > 0; i--)
sink(i);
}
int main(int argc, char *argv[])
{
int n;
while(scanf("%d", &n) != EOF) {
hs = 0;
memset(heap, 0, sizeof(heap));
while(n--) {
int a;
scanf("%d", &a);
insert(a);
}
for(int i = 0; i <= hs; i++)
printf("%d ", heap[i]);
printf("\n");
printf("The Minnum is %d\n", deleteMin());
}
return 0;
}