-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathminIntHeap.cpp
More file actions
129 lines (102 loc) · 2.62 KB
/
minIntHeap.cpp
File metadata and controls
129 lines (102 loc) · 2.62 KB
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
121
122
123
124
125
126
127
128
129
//
// Created by Mayank Parasar on 2020-01-11.
//
/*
* This contains the implemenation of min-Heap data structure
* */
#include <iostream>
#include <vector>
using namespace std;
class minIntHeap {
public:
// minIntHeap(); // default
// minIntHeap(int=10, int=0); // must declare ctor inside class..
int getLeftChildIndex(int parentIndex) { return 2 * parentIndex + 1; }
int getRightChildIndex(int parentIndex) { return 2 * parentIndex+ 2; }
int getParentIndex(int childIndex) { return (childIndex - 1)/ 2;}
bool hasLeftChild(int index) { return getLeftChildIndex(index) < items.size(); }
bool hasRightChild(int index) { return getRightChildIndex(index) < items.size(); }
bool hasParent(int index) { return getParentIndex(index) >= 0; }
int leftChild(int index) { return items[index]; }
int rightChild(int index) { return items[index]; }
int parent(int index) { return items[index]; }
void heapifyUp();
void heapifyDown();
int pop();
void add(int item);
// void swap(int, int);
void print();
private:
// int capacity;
// int size;
vector<int> items;
};
// ctor
//minIntHeap::minIntHeap(int cap, int s) {
// // capacity = cap;
// // size = s;
// items.resize(cap);
//}
void
minIntHeap::print() {
for(auto i : items)
cout << i << " ";
cout << endl;
}
int
minIntHeap::pop() {
int item = items[0];
// items[0] = items[size - 1];
// size--;
items[0] = items.back();
items.pop_back();
heapifyDown();
return item;
}
void
minIntHeap::add(int item) {
// items[size] = item;
// size++;
items.push_back(item);
heapifyUp();
}
//void
//minIntHeap::swap(int index1, int index2) {
// swap(items[index1], items[index2]);
// return;
//}
void
minIntHeap::heapifyUp() {
int index = items.size() - 1;
while(hasParent(index) && parent(index) > items[index]) {
swap(items[getParentIndex(index)], items[index]);
index = getParentIndex(index);
}
}
void
minIntHeap::heapifyDown() {
int index = 0;
while(hasLeftChild(index)) {
int smallerChildIndex = getLeftChildIndex(index);
if(hasRightChild(index) &&
(rightChild(index) < leftChild(index))) {
smallerChildIndex = getRightChildIndex(index);
}
if(items[index] < items[smallerChildIndex]) {
break;
} else {
swap(index, smallerChildIndex);
}
index = smallerChildIndex;
}
}
int main() {
minIntHeap heap;
heap.add(10);
heap.add(15);
heap.add(20);
heap.add(17);
heap.add(8);
heap.print();
return 0;
}