-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHeap Insertion.cpp
More file actions
99 lines (94 loc) · 1.56 KB
/
Heap Insertion.cpp
File metadata and controls
99 lines (94 loc) · 1.56 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
#include<iostream>
#include<vector>
using namespace std;
class Heap
{
vector <int> v;
bool minHeap;
bool compare(int a, int b)
{
if(minHeap)
{
return a < b;
}
else
{
return a > b;
}
}
void heapify(int idx)
{
int left = 2*idx;
int right = left + 1;
int min_idx = idx;
int last = v.size() - 1;
if(left <= last && compare(v[left],v[idx]))
{
min_idx = left;
}
if(right <= last && compare(v[right],v[min_idx]))
{
min_idx = right;
}
if(min_idx != idx)
{
swap(v[idx],v[min_idx]);
heapify(min_idx);
}
}
public:
Heap(int default_size = 10 , bool type = true)
{
v.reserve(default_size);
v.push_back(-1);
minHeap = type;
}
void push(int d)
{
v.push_back(d);
int idx = v.size() -1;
int parent = idx / 2;
//Keep pushing to the top till you reach root node or stop mid way because current element is greater than parent
while(idx > 1 and compare(v[idx],v[parent]))
{
swap(v[idx] , v[parent]);
idx = parent;
parent = parent / 2;
}
}
int top()
{
return v[1];
}
void pop()
{
//Swap the first and the last element
int last = v.size() - 1;
swap(v[1],v[last]);
//Deleting root node
v.pop_back();
heapify(1);
}
bool empty()
{
return v.size()==1;
}
};
int main()
{
Heap h;
//Heap h(10,false) ->can turn it into a max heap
int n;
cin>>n;
for(int i = 0 ; i < n ; i++)
{
int no;
cin>>no;
h.push(no);
}
while (!h.empty())
{
cout<<h.top()<<" ";
h.pop();
}
}