Code Snippets
/

Min-Heap Template

Min-Heap Template

JavaScript still has no built-in priority queue, so most real-world code rolls its own min-heap. This snippet covers a generic comparator-based heap with push and pop, the sift-up and sift-down internals that make both O(log n), and a heapify-from-array helper that builds a heap from an arbitrary input in O(n).

JavaScript
Medium
3 snippets
data-structures
heap
code-template
algorithms

589 views

5

class MinHeap {
    constructor(compare = (a, b) => a - b) {
        this.data = [];
        this.compare = compare;
    }
    get size() { return this.data.length; }
    peek() { return this.data[0]; }
    push(value) {
        this.data.push(value);
        this.#siftUp(this.data.length - 1);
    }
    pop() {
        if (this.data.length === 0) return undefined;
        const top = this.data[0];
        const last = this.data.pop();
        if (this.data.length > 0) {
            this.data[0] = last;
            this.#siftDown(0);
        }
        return top;
    }
    #siftUp(i) {
        while (i > 0) {
            const parent = (i - 1) >>> 1;
            if (this.compare(this.data[i], this.data[parent]) < 0) {
                [this.data[i], this.data[parent]] = [this.data[parent], this.data[i]];
                i = parent;
            } else break;
        }
    }
    #siftDown(i) {
        const n = this.data.length;
        while (true) {
            const left = 2 * i + 1;
            const right = 2 * i + 2;
            let smallest = i;
            if (left < n && this.compare(this.data[left], this.data[smallest]) < 0) smallest = left;
            if (right < n && this.compare(this.data[right], this.data[smallest]) < 0) smallest = right;
            if (smallest === i) break;
            [this.data[i], this.data[smallest]] = [this.data[smallest], this.data[i]];
            i = smallest;
        }
    }
}

const h = new MinHeap();
for (const x of [5, 3, 7, 1, 9, 2]) h.push(x);
const out = [];
while (h.size > 0) out.push(h.pop());
console.log(out); // [1, 2, 3, 5, 7, 9]

The heap is stored as a plain array where parent(i) = (i - 1) / 2 and the children of i live at 2i + 1 and 2i + 2. push appends to the end and sifts up: bubble the new element toward the root while it is smaller than its parent. pop removes the root, moves the last element into its place, and sifts down: swap with the smaller child while invariant is broken. Both operations touch O(log n) levels. The comparator default (a, b) => a - b makes the structure a min-heap; pass (a, b) => b - a for a max-heap.