-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathPriority Queue Class.cpp
102 lines (77 loc) · 1.59 KB
/
Priority Queue Class.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
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
#include<iostream>
using namespace std;
class Priority_Queue{
int index;
int total_size;
int *a;
private:
void heapify(int index){
while(index >1){
int parent = index/2;
if( a[parent] > a[index]){
break;
}
else{
swap(a[parent],a[index]);
index = index>>1;
}
}
return ;
}
void heapifyDown(int index){
int left = 2*index;
int right = left + 1 ;
int mx = index;
if(left <= total_size ){
if( a[left] > a[mx] ){
mx = left;
}
}
if(right <= total_size ){
if(a[right] > a[mx]){
mx = right;
}
}
if(mx!=index){
swap( a[index],a[mx]);
heapifyDown(mx);
}
}
public:
int getSize(){
return total_size;
}
Priority_Queue(int s){
index=1;
a = new int[s+1];
total_size = 0;
}
void push(int no){
a[index] = no;
heapify(index);
index++;
total_size++;
}
int top(){
return a[1];
}
void pop(){
swap(a[1],a[index-1]);
index--;
total_size--;
heapifyDown(1);
}
};
int main(){
Priority_Queue pq(100);
int a[]= {3,2,4,6,7,8,6,7,10};
int n = sizeof(a)/sizeof(int);
for(int i=0;i<n;i++){
pq.push(a[i]);
}
while(pq.getSize()){
cout<<pq.top()<<endl;
pq.pop();
}
return 0;
}