Skip to content

Commit 64f5eb0

Browse files
authored
Create MaxPriorityQueue.cpp
1 parent 364add2 commit 64f5eb0

File tree

1 file changed

+116
-0
lines changed

1 file changed

+116
-0
lines changed
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
2+
3+
int main() {
4+
PriorityQueue pq;
5+
int choice;
6+
cin >> choice;
7+
while(choice != -1) {
8+
switch(choice) {
9+
case 1 : // insert
10+
int element;
11+
cin >> element;
12+
pq.insert(element);
13+
break;
14+
case 2 : // getMax
15+
cout << pq.getMax() << endl;
16+
break;
17+
case 3 : // removeMax
18+
cout << pq.removeMax() << endl;
19+
break;
20+
case 4 : // size
21+
cout << pq.getSize() << endl;
22+
break;
23+
case 5 : // isEmpty
24+
if(pq.isEmpty()) {
25+
cout << "true" << endl;
26+
}
27+
else {
28+
cout << "false" << endl;
29+
}
30+
default :
31+
return 0;
32+
}
33+
cin >> choice;
34+
}
35+
}
36+
37+
#include <vector>
38+
class PriorityQueue {
39+
vector<int> pq;
40+
public:
41+
PriorityQueue(){
42+
43+
}
44+
int getSize(){
45+
return pq.size();
46+
}
47+
48+
bool isEmpty() {
49+
return pq.size() == 0;
50+
}
51+
52+
int getMax() {
53+
if(isEmpty()) {
54+
return 0; // Priority Queue is empty
55+
}
56+
return pq[0];
57+
}
58+
59+
void insert(int element) {
60+
pq.push_back(element);
61+
62+
int childIndex = pq.size() - 1;
63+
64+
while(childIndex > 0) {
65+
int parentIndex = (childIndex - 1) / 2;
66+
67+
if(pq[childIndex] > pq[parentIndex]) {
68+
int temp = pq[childIndex];
69+
pq[childIndex] = pq[parentIndex];
70+
pq[parentIndex] = temp;
71+
}
72+
else {
73+
break;
74+
}
75+
childIndex = parentIndex;
76+
}
77+
78+
}
79+
80+
81+
int removeMax() {
82+
if(pq.size() == 0)
83+
return 0;
84+
int minindex;
85+
int todel = pq[0];
86+
pq[0] = pq[pq.size() - 1];
87+
pq.pop_back();
88+
89+
int parentindex = 0;
90+
int childindex1 = 1;
91+
int childindex2 = 2;
92+
while(childindex1 < pq.size()){
93+
94+
if(pq[childindex1] > pq[parentindex] || pq[childindex2] > pq[parentindex]){
95+
if(pq[childindex1] > pq[childindex2])
96+
minindex = childindex1;
97+
else
98+
minindex = childindex2;
99+
100+
int temp = pq[parentindex];
101+
pq[parentindex] = pq[minindex];
102+
pq[minindex] = temp;
103+
104+
parentindex = minindex;
105+
childindex1 = 2*parentindex + 1;
106+
childindex2 = 2*parentindex + 2;
107+
108+
}else
109+
break;
110+
}
111+
return todel;
112+
}
113+
114+
115+
116+
};

0 commit comments

Comments
 (0)