forked from aryan-02/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Max_Heap.cpp
53 lines (53 loc) · 1.27 KB
/
Max_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
#include <iostream>
#include <cmath>
#include <queue>
using namespace std;
//This is an implementation of a max heap. It is available as a priority queue in C++ STL.
vector<int> Heap;
int Parent(int Index){
return (Index-1)/2;
}
void push(int ValueToPush){
Heap.push_back(ValueToPush);
int CurrentIndex = Heap.size()-1;
while(CurrentIndex>0){
if(Heap[CurrentIndex]>Heap[Parent(CurrentIndex)]){
int temp = Heap[Parent(CurrentIndex)];
Heap[Parent(CurrentIndex)] = Heap[CurrentIndex];
Heap[CurrentIndex] = temp;
}
else{
return;
}
}
}
int top(){
return Heap[0];
}
void pop(){
Heap[0] = Heap[Heap.size() - 1];
Heap.pop_back();
int CurrentIndex = 0;
int Child = 0;
while((CurrentIndex*2 + 1)<Heap.size()){
Child = CurrentIndex*2 + 1;
if(Child+1<Heap.size() && Heap[Child+1]>Heap[Child]) Child++;
int temp = Heap[Child];
Heap[Child] = Heap[CurrentIndex];
Heap[CurrentIndex] = temp;
CurrentIndex = Child;
}
}
int main(){
int Size;
cin>>Size;
int Array[Size];
for(int i =0 ;i<Size;i++){
cin>>Array[i];
push(Array[i]);
}
for(int i = Size-1;i>=0;i--){
Array[i] = top();
pop();
}
}