-
Notifications
You must be signed in to change notification settings - Fork 0
/
min_heap.cpp
120 lines (102 loc) · 2.61 KB
/
min_heap.cpp
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
#include "grid.h"
// Prototype of a utility function to swap two integers
void swap(Cell *x, Cell *y);
// A class for Min Heap
// Constructor: Builds a heap from a given array a[] of given size
MinHeap::MinHeap(int cap)
{
heap_size = 0;
capacity = cap;
harr = new Cell[cap];
}
MinHeap::~MinHeap(){
delete(harr);
}
// Inserts a new key 'k'
void MinHeap::insertKey(Cell k)
{
if (heap_size == capacity)
{
cout << "\nOverflow: Could not insertKey\n";
return;
}
// First insert the new key at the end
heap_size++;
int i = heap_size - 1;
harr[i] = k;
// Fix the min heap property if it is violated
while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
// Decreases value of key at index 'i' to new_val. It is assumed that
// new_val is smaller than harr[i].
void MinHeap::decreaseKey(Cell u, int new_val)
{
int i = GetIndex(u);
harr[i].mDistance = new_val;
while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
// Method to remove minimum element (or root) from min heap
Cell MinHeap::extractMin()
{
if (heap_size == 1)
{
heap_size--;
return harr[0];
}
// Store the minimum value, and remove it from heap
Cell root = harr[0];
harr[0] = harr[heap_size-1];
heap_size--;
MinHeapify(0);
return root;
}
// This function deletes key at index i. It first reduced value to minus
// infinite, then calls extractMin()
void MinHeap::deleteKey(Cell u)
{
decreaseKey(u, INT_MIN);
extractMin();
}
// A recursive method to heapify a subtree with the root at given index
// This method assumes that the subtrees are already heapified
void MinHeap::MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l].mDistance < harr[i].mDistance)
smallest = l;
if (r < heap_size && harr[r].mDistance < harr[smallest].mDistance)
smallest = r;
if (smallest != i)
{
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
}
}
int MinHeap::GetIndex(Cell u){
for(int i=0; i<capacity; i++){
if(harr[i].GetX() == u.GetX() && harr[i].GetY() == u.GetY()){
return i;
}
}
return -1;
}
bool MinHeap::Empty(){
return (heap_size == 0);
}
// A utility function to swap two elements
void swap(Cell *x, Cell *y)
{
Cell temp = *x;
*x = *y;
*y = temp;
}