From 79a7c7d68e9ed7023842bbf340851beaec480b84 Mon Sep 17 00:00:00 2001 From: satwik jain <69858899+satwik104@users.noreply.github.com> Date: Wed, 2 Mar 2022 21:30:10 +0530 Subject: [PATCH] Update remove min :: min heap sort I hope u will like it....i proposed this because i find your solution a little complex and hard to dry run..hope u accept the solution --- priority queues/remove min :: min heap sort | 39 +++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/priority queues/remove min :: min heap sort b/priority queues/remove min :: min heap sort index 8a8ee84..05d81ed 100644 --- a/priority queues/remove min :: min heap sort +++ b/priority queues/remove min :: min heap sort @@ -48,7 +48,7 @@ class PriorityQueue { } - + /* int removeMin() { // Complete this function if(pq.size()==0) @@ -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(LCIpq[LCI]) + minIndex = LCI; + //check if rci is also with in limit or not + if(RCIpq[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; + } };