-
Notifications
You must be signed in to change notification settings - Fork 47
/
Binary-heap
67 lines (54 loc) · 1.4 KB
/
Binary-heap
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
int MinHeap::extractMin()
{
if(heap_size == 0)
return -1;
int minVal = harr[0];
swap(harr[0],harr[--heap_size]);
MinHeapify(0);
return minVal;
}
//Function to delete a key at ith index.
void MinHeap::deleteKey(int i)
{
if(i >= heap_size)
return;
decreaseKey(i, INT_MIN);
extractMin();
}
//Function to insert a value in Heap.
void MinHeap::insertKey(int k)
{
if(heap_size == capacity)
return;
harr[heap_size++] = k;
int i = heap_size-1;
while(parent(i) >= 0 && (harr[i] < harr[parent(i)]))
{
swap(harr[i],harr[parent(i)]);
i = parent(i);
}
}
//Function to change value at ith index and store that value at first index.
void MinHeap::decreaseKey(int i, int new_val)
{
harr[i] = new_val;
while (i != 0 && harr[parent(i)] > harr[i]) {
swap(harr[i], harr[parent(i)]);
i = parent(i);
}
}
/* You may call below MinHeapify function in
above codes. Please do not delete this code
if you are not writing your own MinHeapify */
void MinHeap::MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i]) smallest = l;
if (r < heap_size && harr[r] < harr[smallest]) smallest = r;
if (smallest != i) {
swap(harr[i], harr[smallest]);
MinHeapify(smallest);
}
}