Skip to content

Update remove min :: min heap sort #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions priority queues/remove min :: min heap sort
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class PriorityQueue {

}


/*
int removeMin() {
// Complete this function
if(pq.size()==0)
Expand Down Expand Up @@ -110,6 +110,41 @@ class PriorityQueue {
}
return m;
}
*/
//I feel this code is much more easy to understand and also organised


int removeMin() {
int ans = pq[0];//placing root node which is min in the ans, which we will return in last

pq[0]=pq[pq.size()-1];//coping last element in place of root node

pq.pop_back();//removing the last element space

int pi = 0,LCI = 2*pi+1,RCI = 2*pi+2;//parent index, left child index, right child index

// now we need to perform down hepify
//we need to get minimum of parent and children

while(LCI<pq.size())//we check if lci is within limit or not
{
int minIndex = pi;//minIndex will be the index carrying the min value...out of 3
if(pq[minIndex]>pq[LCI])
minIndex = LCI;
//check if rci is also with in limit or not
if(RCI<pq.size() && pq[minIndex]>pq[RCI])
minIndex = RCI;
//if both of the above if do not run then it means we dont need to swap anymore
if(pi == minIndex)
break;
//now we got the index with which we need to swapp so do it
int temp = pq[pi];
pq[pi] = pq[minIndex];
pq[minIndex] = temp;
//now update pi,lci,rci
pi=minIndex;//because after swapping the number is at minIndex...so it will be our new pi
LCI=2*pi+1;
RCI=2*pi+2;
}
return ans;
}
};