JavaScript Snippet

Min-Heap Template

Difficulty: Medium

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).

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

588 views

5

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.