-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap.c
57 lines (42 loc) · 867 Bytes
/
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
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
typedef struct {
int heap[MAX];
int heapSize;
}heapType;
heapType* createHeap() {
heapType* h = (heapType*)malloc(sizeof(heapType));
h->heapSize = 0;
return h;
}
void insertHeap(heapType* h, int elem) {
h->heapSize = h->heapSize + 1;
int i = h->heapSize;
while ((i != 1) && (elem > h->heap[i / 2])) {
h->heap[i] = h->heap[i / 2];
i /= 2;
}
h->heap[i] = elem;
}
void deleteHeap(heapType* h) {
int parent, child, temp;
temp = h->heap[h->heapSize];
h->heapSize = h->heapSize - 1;
parent = 1;
child = 2;
while (child <= h->heapSize) {
if ((child < h->heapSize) && (h->heap[child] < h->heap[child + 1])) {
child++;
}
if (temp >= h->heap[child]) {
break;
}
else {
h->heap[parent] = h->heap[child];
parent = child;
child *= 2;
}
}
h->heap[parent] = temp;
}