Explore Library
Code Quiz

Min-Heap Sift-Down Child Indices

Spot the child-index bug in a binary min-heap sift-down operation stored in a 0-indexed array.

Codejavascript
// Min-heap stored in a 0-indexed array
function siftDown(heap, i) {
  const n = heap.length;
  while (true) {
    let smallest = i;
    let left = 2 * i;      // left child
    let right = 2 * i + 1; // right child

    if (left < n && heap[left] < heap[smallest]) smallest = left;
    if (right < n && heap[right] < heap[smallest]) smallest = right;

    if (smallest === i) break;
    [heap[i], heap[smallest]] = [heap[smallest], heap[i]];
    i = smallest;
  }
}

What is the bug in this sift-down implementation?