-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap_1.cpp
More file actions
100 lines (84 loc) · 2.09 KB
/
Heap_1.cpp
File metadata and controls
100 lines (84 loc) · 2.09 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
#include <iostream>
#include <vector>
using namespace std;
//Implementation of Heap using Vector(Dynamic Array)
class Heap{
vector<int> v;
//Configuration
bool minHeap;
bool compare(int a,int b){
if(minHeap){
return a<b;
}
else{
return a>b;
}
}
void heapify(int i)
{
int left=2*i;
int right=2*i+1;
//Assume current index to min
int minIndex=i;
if(left<v.size() && compare(v[left],v[i]))
{
minIndex=left;
}
if(right<v.size() && compare(v[right],v[minIndex]))
{
minIndex=right;
}
if(minIndex!=i)
{
swap(v[i],v[minIndex]);
heapify(minIndex);
}
}
public:
Heap(bool type=true){
minHeap = type;
//Block the 0th index
v.push_back(-1);
}
void push(int data){
//Insert at Last
v.push_back(data);
//Take that element to correct position restore the heap property
int index = v.size() - 1;
int parent = index/2;
while(index>1 && compare(v[index],v[parent]) ){
swap(v[index],v[parent]);
index = parent;
parent = parent/2;
}
}
bool empty(){
return v.size()==1;
}
int top(){
return v[1];
}
void pop()
{
//remove topmost element
int last=v.size()-1;
swap(v[1],v[last]);
v.pop_back();
heapify(1);
}
};
int main() {
Heap h(true);
h.push(5);
h.push(15);
h.push(2);
h.push(20);
h.push(3);
//cout<<h.top()<<endl;
while(!h.empty())
{
cout<<h.top()<<endl;
h.pop();
}
return 0;
}