Question

I have been learning JavaScript through the eloquentjavascript website, and came some code I can't seem to understand:

remove: function(node) {
    var length = this.content.length;
    // To remove a value, we must search through the array to find
    // it.
    for (var i = 0; i < length; i++) {
      if (this.content[i] != node) continue;
      // When it is found, the process seen in 'pop' is repeated
      // to fill up the hole.
      var end = this.content.pop();
      // If the element we popped was the one we needed to remove,
      // we're done.
      if (i == length - 1) break;
      // Otherwise, we replace the removed element with the popped
      // one, and allow it to float up or sink down as appropriate.
      this.content[i] = end;
      this.bubbleUp(i);
      this.sinkDown(i);
      break;
    }
  },

My question is - Why does this function need to call bubbleUp()? if end was the last value on the binary heap, and every value pushed onto the heap calls bubbleUp when it is added through the push() method, how could it be possible that the end value has a lower score than the value at i? I am new to data structures and can't seem to figure this out.

Was it helpful?

Solution

Imagine a min-heap like so:

       1
   10      2
 18  20  3   4

Now, say you remove 20. The code you have basically sticks 4 in its place.

       1
   10      2
 18   4  3

Since 4 < 10, it has to bubble up in order to satisfy the requirements of a min-heap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top