-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinHeap.c
77 lines (66 loc) · 1.51 KB
/
MinHeap.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
#include<stdio.h>
#include<limits.h>
// Declare heap globally so we don't have to pass it.
int heap[1000000], heapSize;
void Init()
{
heapSize = 0;
heap[0] = -INT_MAX;
}
void Insert(int element)
{
int now = ++heapSize;
while (heap[now / 2] > element)
{
heap[now] = heap[now / 2];
now /= 2;
}
heap[now] = element;
}
int DeleteMin()
{
int minElement, lastElement, child, now;
minElement = heap[1];
lastElement = heap[heapSize--];
for (now = 1; now * 2 <= heapSize; now = child)
{
// Start with left child.
child = now * 2;
if (child != heapSize && heap[child + 1] < heap[child])
{
child++;
}
if (lastElement > heap[child])
{
heap[now] = heap[child];
}
else
{
break;
}
}
heap[now] = lastElement;
return minElement;
}
int main()
{
Init();
// Let user populate the heap elements.
int number_of_elements;
printf("Program to demonstrate Heap:\nEnter the number of elements: ");
scanf("%d", &number_of_elements);
int iter, element;
printf("Enter the elements: ");
for (iter = 0; iter < number_of_elements; iter++)
{
scanf("%d", &element);
Insert(element);
}
// Remove and print minimum elements until heap is empty.
for (iter = 0; iter < number_of_elements; iter++)
{
printf("%d ", DeleteMin());
}
printf("\n");
return 0;
}