0

Currently trying to grasp the Min Heap with Repl here: https://repl.it/@Stylebender/Minheap#index.js

Min Heap has a capacity of 5.

Once I insert the 6th element (50) we swap the positions of the elements at index 0 and index 5 and eject the smallest element from the heap leaving the heap as:

[ 50, 10, 20, 40, 30]

My specific query has to deal with Lines 39-40.

As you can see from the console log, the first time we call the trickeDown() method, min (0) which represents the index position of 50 becomes leftChild and ends up swapping positions with index 1 with the following result:

[ 50, 10, 20, 40, 30]

However, on the second call of the trickleDown() method, 50 which is at index 1 assumes the position of rightChild and swaps positions with index 4 to form the final heap as below:

[ 10, 30, 20, 40, 50]

Maybe I'm just missing something but I'm not sure why min decided to become leftChild in the first run and rightChild in the second run since wouldn't 50, as the largest element within the min heap satisfy both the For Loops every time the method is invoked?

Mike Chan
  • 167
  • 1
  • 11
  • Welcome to Stack Overflow. Please post needed code in the Question, not just a link to the needed code. – Beta Aug 12 '20 at 16:19

1 Answers1

1

In the first call, we comparing 50, 10 and 20.
min begins at 0, indicating the 50.
10 is less than 50, so min becomes 1.
20 is not less than 10, so min does not change.
We have found the minimum: 10.

In the second call, we compare 50, 40 and 30.
min begins at 1, indicating the 50.
40 is less than 50, so min becomes 3.
30 is less than 40, so min becomes 4.
We have found the minimum: 30.

It is not sufficient to find an element less than 50; we must find the minimum. To swap 50 and 20 would not produce a valid min-heap.

Beta
  • 96,650
  • 16
  • 149
  • 150