-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxHeap.cpp
More file actions
108 lines (98 loc) · 2.37 KB
/
maxHeap.cpp
File metadata and controls
108 lines (98 loc) · 2.37 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
#include<iostream>
#include<vector>
using namespace std;
class Heap{
private:
vector<int> heap;
int currentPos = -1;
public:
void insert(int data){
heap.push_back(data);
currentPos+=1;
heapifyUp(currentPos);
}
void heapifyUp(int index){
int parent = (index-1)/2;
while(parent >=0 && (heap[parent] < heap[index])){
int temp = heap[parent];
heap[parent] = heap[index];
heap[index] = temp;
index = parent;
parent = (index-1)/2;
}
}
void poll(){
heap[0] = heap.back();
heap.pop_back();
currentPos -= 1;
heapifyDown(0);
}
void remove(int data){
int index = findIndex(data);
if(index==-1){
cout<<"Element not present"<<endl;
return;
}
heap[index] = heap.back();
heap.pop_back();
currentPos -= 1;
heapifyDown(index);
heapifyUp(index);
}
int findIndex(int key){
for(int i=0; i<heap.size(); i++){
if(heap[i]==key){
return i;
}
}
return -1;
}
void heapifyDown(int start){
int left = 2*start + 1;
int right = 2*start + 2;
int largest = start;
if(left < heap.size() && heap[left] > heap[largest]){
largest = left;
}
if(right < heap.size() && heap[right] > heap[largest]){
largest = right;
}
if(largest!=start){
int temp = heap[largest];
heap[largest] = heap[start];
heap[start] = temp;
heapifyDown(largest);
}
}
void traverse(){
int i = 0;
for(i=0; i<heap.size(); i++){
cout<<heap[i]<<" ";
}
}
int peek(){
if(currentPos==-1){
return -1;
}
return heap[0];
}
int size(){
return heap.size();
}
};
int main(){
//btw you can use priority_queue<int, vector<int>, greater<int>> heap;
//.top(), .pop(), push(), .size();
//int arr[] = {3554,2227, 8866, 9890, 212 ,8669 ,2423, 7651 ,3878, 3379, 1419, 6134, 5767, 859, 2848, 9309,1449, 8408, 8041, 3367 ,6676, 6382 ,4136, 4871};
Heap *h = new Heap();
h->insert(1);
h->insert(3);
h->insert(2);
h->insert(5);
h->insert(6);
h->insert(4);
h->insert(7);
h->poll();
h->traverse();
return 0;
}