A heap answers one question instantly: "what's the smallest (or largest)?" The min-heap invariant: every parent ≤ both children. That's weaker than a BST's total order, siblings and cousins are unordered, but it guarantees the minimum is always at the root, and it's strong enough to maintain in O(log n) per operation. This structure is called a priority queue: instead of FIFO or LIFO, the most urgent element leaves first.
Insert: place the new element at the next open slot (bottom level), then bubble it UP while it's smaller than its parent. Extract-min: remove the root, move the last element to the root, then sift it DOWN by swapping with its smaller child. Each operation touches one root-to-leaf path, O(log n). The delightful implementation detail: none of this needs pointers. A heap lives in a plain array where the children of index i are 2i+1 and 2i+2 and the parent is ⌊(i−1)/2⌋, the tree is just an interpretation of the array's order.
Array-backed min-heap
class MinHeap {
#a = [];
get size() { return this.#a.length; }
peek() { return this.#a[0]; } // O(1), the whole point
push(v) { // O(log n)
this.#a.push(v);
let i = this.#a.length - 1;
while (i > 0) { // bubble up
const parent = (i - 1) >> 1;
if (this.#a[parent] <= this.#a[i]) break;
[this.#a[parent], this.#a[i]] = [this.#a[i], this.#a[parent]];
i = parent;
}
}
pop() { // O(log n)
const top = this.#a[0];
const last = this.#a.pop();
if (this.#a.length) {
this.#a[0] = last;
let i = 0;
for (;;) { // sift down
const l = 2 * i + 1, r = 2 * i + 2;
let smallest = i;
if (l < this.#a.length && this.#a[l] < this.#a[smallest]) smallest = l;
if (r < this.#a.length && this.#a[r] < this.#a[smallest]) smallest = r;
if (smallest === i) break;
[this.#a[i], this.#a[smallest]] = [this.#a[smallest], this.#a[i]];
i = smallest;
}
}
return top;
}
}| Operation / case | Cost | Notes |
|---|---|---|
| peek (min/max) | O(1) | root |
| insert | O(log n) | bubble up one path |
| extract min/max | O(log n) | sift down one path |
| build from n items (heapify) | O(n) | bottom-up construction beats n inserts |
| search arbitrary value | O(n) | heaps are NOT for searching |