function push(heap: number[], key: number) {heap.push(key);
let index = heap.length - 1;
while (index > 0 && heap[index] > heap[parent(index)]) {swap(heap, index, parent(index));
index = parent(index);
}
}
function pop(heap: number[]): number {const top = heap[0];
heap[0] = heap[heap.length - 1];
heap.pop();
siftDown(heap, 0);
return top;
}
function siftDown(heap: number[], index: number) { while (true) {const left = 2 * index + 1, right = left + 1;
let largest = index;
if (left < heap.length && heap[left] > heap[largest]) largest = left;
if (right < heap.length && heap[right] > heap[largest]) largest = right;
if (largest === index) return;
swap(heap, index, largest);
index = largest;
}
}
Push 24: append it at index 0, the next free slot of the complete tree.
Understanding Binary heap
The idea
A binary heap is a complete binary tree, every level full except the last, which fills left to right, stored in an array with no pointers at all: the children of index i sit at 2i + 1 and 2i + 2, and its parent at ⌊(i − 1) / 2⌋. The one rule is that every parent is at least as large as its children, so the maximum is always at index 0.
Push appends the key at the end and sifts it up, swapping with its parent while it is larger. Pop takes the root, moves the last leaf into its place and sifts it down, swapping with the larger child while one of them is larger. Both walk one root-to-leaf path, so both cost the height, log₂ n.
The four stages
Complexity
Versus its siblings
Pseudocode
PUSH(heap, key)
append key; index ← last
while index > 0 and heap[index] > heap[parent]: swap them; index ← parent
POP(heap)
top ← heap[0]; move the last key to index 0; shrink
index ← 0; while a child is larger: swap with the larger child; descend
return top
When to use
Pitfalls
History
J. W. J. Williams introduced the binary heap in 1964 as the engine of heapsort, and Robert Floyd improved the construction to linear time the same year. The array layout without pointers is what made it practical; Fibonacci and pairing heaps later improved the asymptotics of decrease-key but rarely beat it in practice.