-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeaps_CB.cpp
More file actions
73 lines (60 loc) · 1.3 KB
/
Copy pathHeaps_CB.cpp
File metadata and controls
73 lines (60 loc) · 1.3 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
#include <bits/stdc++.h>
using namespace std;
vector<int> v;
void insert(int data) {
v.push_back(data);
int index = v.size() - 1;
int parent = index / 2;
while (index > 1 && v[parent] < v[index]) {
swap(v[index], v[parent]);
index = parent;
parent = parent / 2;
}
}
void heapify(int i) {
int left, right;
left = 2 * i;
right = 2 * i + 1;
int maxIndex = i;
if (left < v.size() && v[left] > v[i])
maxIndex = left;
if (right < v.size() && v[right] > v[maxIndex])
maxIndex = right;
if (maxIndex != i) {
swap(v[i], v[maxIndex]);
heapify(maxIndex);
}
}
void pop() {
int last = v.size() - 1;
swap(v[1], v[last]);
v.pop_back();
heapify(1);
}
void showTop() {
cout << v[1] << endl;
}
void levelOrder_Display() {
for (int i = 1; i < v.size(); i++) {
cout << v[i] << " ";
}
cout<<"\n";
}
int main()
{
v.push_back(-1); /*Element at Index '0' is not to be used*/
insert(54);
insert(45);
insert(36);
insert(27);
insert(29);
insert(18);
insert(21);
insert(11);
showTop();
levelOrder_Display();
pop();
showTop();
levelOrder_Display();
return 0;
}