0

I'm trying to implement a remove method for my binary heap implementation.

class Node {
  constructor(priority) {
    this.priority = priority;
  }
}

class PriorityQueue {
  constructor() {
    this.heap = [null];
  }

remove() {

  const toRemove = this.heap[1];
  this.heap[1] = this.heap.pop();  
  let currentIdx = 1;
  let [left, right] = [2*currentIdx, 2*currentIdx + 1]; 
  let currentChildIdx = this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left; //Assess which child node has higher priority

  while (this.heap[currentChildIdx] && this.heap[currentIdx].priority <= this.heap[currentChildIdx].priority) { 
    let currentNode = this.heap[currentIdx]
    let currentChildNode = this.heap[currentChildIdx];
    this.heap[currentChildIdx] = currentNode;
    this.heap[currentIdx] = currentChildNode;
    currentIdx = this.heap.indexOf(currentNode);
  }
  return toRemove;
}


}

However, I'm not sure how to properly update the value of currentIdx and currentChildIdx when I'm running my while loop. In fact, the code seems to stop working when I try to update the value of currentIdx

currentIdx = this.heap.indexOf(currentNode);

Any tips on what I'm doing wrong?

Full code here: https://repl.it/@Stylebender/Binary-Heap-Naive

KamiWar
  • 41
  • 5

1 Answers1

0

In the loop, once you swap the values for currentIdx and currentChildIdx, then you should assign currentIdx = currentChildIdx.

And once you change currentIdx, you need to recompute the left and right child indexes and a new currentChildIdx.

The basic idea is:

while currentIdx < heap_length
    currentChildIdx = index of largest child
    if (heap[currentIdx] >= heap[currentChildIdx])
        break; // node is now in the right place
    swap(heapCurrentIdx, heap[currentChildIdx)
    currentIdx = currentChildIdx

My suggestion is that you build that basic structure, and then single-step it in the debugger to make sure it's working as expected.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351