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 1366ab4

Browse files
Create Code : Remove Min
1 parent 967fd5d commit 1366ab4

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

‎Priority Queues/Code : Remove Min

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

0 commit comments

Comments
(0)

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