Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1ee9775

Browse files
Create Code : Max Priority Queue
1 parent 1366ab4 commit 1ee9775

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#include<climits>
2+
#include<vector>
3+
class PriorityQueue {
4+
vector<int> pq;
5+
6+
public:
7+
PriorityQueue() {
8+
// Implement the constructor here
9+
}
10+
11+
/**************** Implement all the public functions here ***************/
12+
13+
void insert(int element) {
14+
pq.push_back(element);
15+
int childindex=pq.size()-1;
16+
17+
while(childindex>0){
18+
int parentindex=(childindex-1)/2;
19+
if(pq[parentindex]<pq[childindex]){
20+
int temp=pq[parentindex];
21+
pq[parentindex]=pq[childindex];
22+
pq[childindex]=temp;
23+
}
24+
else{
25+
break;
26+
}
27+
childindex=parentindex;
28+
}
29+
}
30+
31+
int getMax() {
32+
if(isEmpty()){
33+
return INT_MIN;
34+
}
35+
return pq[0];
36+
}
37+
38+
int removeMax() {
39+
if(isEmpty()){
40+
return INT_MIN;
41+
}
42+
int ans=pq[0];
43+
pq[0]=pq[pq.size()-1];
44+
pq.pop_back();
45+
int parentindex=0;
46+
int lci=2*parentindex+1;
47+
int rci=2*parentindex+2;
48+
while(lci<pq.size()){
49+
int maxIndex=parentindex;
50+
if(pq[maxIndex]<pq[lci]){
51+
maxIndex=lci;
52+
}
53+
if(rci<pq.size()&&pq[maxIndex]<pq[rci]){
54+
maxIndex=rci;
55+
}
56+
if(maxIndex==parentindex){
57+
break;
58+
}
59+
int temp=pq[parentindex];
60+
pq[parentindex]=pq[maxIndex];
61+
pq[maxIndex]=temp;
62+
parentindex=maxIndex;
63+
lci=2*parentindex+1;
64+
rci=2*parentindex+2;
65+
}
66+
return ans;
67+
}
68+
69+
int getSize() {
70+
if(isEmpty()){
71+
return 0;
72+
}
73+
return pq.size();
74+
}
75+
76+
bool isEmpty() {
77+
return pq.size()==0;
78+
}
79+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /