-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathbasicHeapTemplate.h
92 lines (75 loc) · 1.65 KB
/
basicHeapTemplate.h
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
#include <iostream>
using namespace std;
struct Heap
{
int *heapArr;
int heapCapacity;
int currentHeapSize;
int shrunkenSize;
};
bool hasParent(int index)
{
if (index <= 0)
return false;
return true;
}
void ensureExtraCapacity(Heap *hp)
{
if (hp->currentHeapSize >= hp->heapCapacity)
{
hp->heapCapacity = 2 * hp->heapCapacity;
}
return;
}
int getParentIndex(int childIndex)
{
return (childIndex / 2);
}
int getLeftChildIndex(Heap *hp, int i)
{
int left = 2 * i;
if (left >= hp->currentHeapSize)
return -1;
return left;
}
int getRightChildIndex(Heap *hp, int i)
{
int left = (2 * i) + 1;
if (left >= hp->currentHeapSize)
return -1;
return left;
}
bool hasLeftChild(Heap *hp, int index)
{
if (index > hp->currentHeapSize || index <= 0)
return false;
return (hp->heapArr[2 * index] == INT_MAX) ? false : true;
}
bool hasRightChild(Heap *hp, int index)
{
if (index > hp->currentHeapSize || index <= 0)
return false;
return (hp->heapArr[(2 * index) + 1] == INT_MAX) ? false : true;
}
void printHeap(Heap *hp)
{
cout << endl;
for (int t = 1; t < (hp->currentHeapSize / 2) + 1; t++)
{
cout << hp->heapArr[t] << " -> ";
cout << " Left Child : ";
cout << hp->heapArr[(2 * t)] << '\t';
cout << " Right Child : ";
cout << hp->heapArr[(2 * t) + 1] << '\t';
cout << endl;
}
cout << endl;
return;
}
void printHeapAsArray(Heap *hp)
{
for (int t = 1; t <= hp->currentHeapSize + hp->shrunkenSize + 1; t++)
cout << hp->heapArr[t] << " ";
cout << endl;
return;
}