-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathHeap.cpp
99 lines (85 loc) · 2.03 KB
/
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
#include<bits/stdc++.h>
using namespace std;
class Heap {
public:
vector<int> a;
int sz = 0;
int parent(int x) {
return (x-1)/2;
}
int leftChild(int x) {
return 2*x+1;
}
int rightChild(int x) {
return 2*x+2;
}
void push(int val){
int ind = sz;
cout<<"pushing at at index = "<<ind<<endl;
a.push_back(val);
sz++;
while(ind != 0) {
if(a[ind] > a[parent(ind)]) {
cout<<"swapping it with parent = "<<parent(ind)<<endl;
swap(a[ind], a[parent(ind)]);
ind = parent(ind);
} else {
break;
}
}
}
int top() {
if(isEmpty()) {
return INT_MIN;
}
return a[0];
}
void pop() {
a[0] = a[sz-1];
sz--;
a.pop_back();
int ind = 0;
while(true){
int cur = a[ind];
int lc = leftChild(ind) < sz ? a[leftChild(ind)] : INT_MIN;
int rc = rightChild(ind) < sz ? a[rightChild(ind)] : INT_MIN;
int maximum = max({cur, lc, rc});
if(maximum == cur) break;
if (maximum == lc){
cout<<"swapping it with leftChild = "<<leftChild(ind)<<endl;
swap(a[ind], a[leftChild(ind)]);
ind = leftChild(ind);
} else {
cout<<"swapping it with rightChild = "<<rightChild(ind)<<endl;
swap(a[ind], a[rightChild(ind)]);
ind = rightChild(ind);
}
}
}
bool isEmpty() {
return size() == 0;
}
int size() {
return sz;
}
void display() {
for(int x: a) {
cout<<x<<" -- ";
}
cout<<endl;
}
}heap;
signed main(){
heap.push(100);
heap.display();
heap.push(20);
heap.display();
heap.push(35);
heap.display();
heap.push(50);
heap.display();
heap.push(200);
heap.display();
heap.pop();
heap.display();
}