Binary heap

A complete binary tree stored in an array where every parent is smaller than its children, giving the minimum in O(1) and inserts and removals in O(log n).

Description

A binary heap keeps the smallest item (in a min-heap) or largest item (in a max-heap) at the top, always. It's the standard way to implement a priority queue: a queue where you always take the most urgent item next, not the oldest.

The heap is a complete binary tree: every level is full except possibly the last, which fills from left to right. That shape means it can be stored in a plain array with no pointers. For the item at index i, its children are at 2i + 1 and 2i + 2, and its parent at ⌊(i − 1) / 2⌋.

The heap property says every parent is no larger than its children (in a min-heap). It doesn't sort the whole tree, only each parent against its children, which is why heaps are cheap to maintain.

To push, add the new item at the end and sift it up: swap it with its parent while it's smaller. To pop the minimum, take the root, move the last item to the root, and sift it down: swap it with its smaller child until both children are larger. Each takes at most the height of the tree, O(log n).

How it works

5812422331175081122423234315176

A min-heap: the tree, and the array that stores it

  1. index 0: 5 (root)
  2. index 1: 8, parent 5
  3. index 2: 12, parent 5
  4. index 3: 42, parent 8
  5. index 4: 23, parent 8
  6. index 5: 31, parent 12
  7. index 6: 17, parent 12
A min-heap: the tree, and the array that stores it

Step through: seven pushes, then two pops

empty

Step 1 of 24Start with an empty min-heap.

0 comparisons, 0 swaps

Complexity

OperationAverageWorst
Peek (minimum)O(1)O(1)
PushOn average a new item sifts up only a level or two.O(1)O(log n)
Pop (minimum)O(log n)O(log n)
Build from n itemsSifting down from the middle, not n separate pushes.O(n)O(n)
Search for any itemA heap isn't ordered for search.O(n)O(n)

Space: O(n)

Because the heap lives in one contiguous array, it's compact and cache-friendly, which makes it faster in practice than pointer-based priority queues with the same Big-O.

TypeScript implementation

A generic min-heap backed by an array, with a comparison function so it also works as a max-heap or on objects.

binary-heap.ts
// A binary min-heap stored in an array. The comparison function makes it
// reusable as a max-heap or for objects (for example, tasks by priority).

export class BinaryHeap<T> {
  private items: T[] = [];
  private compare: (a: T, b: T) => number;

  constructor(compare: (a: T, b: T) => number = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) {
    this.compare = compare;
  }

  get size(): number {
    return this.items.length;
  }

  peek(): T | undefined {
    return this.items[0];
  }

  push(value: T): void {
    this.items.push(value);
    this.siftUp(this.items.length - 1);
  }

  pop(): T | undefined {
    const top = this.items[0];
    const last = this.items.pop();
    if (this.items.length && last !== undefined) {
      this.items[0] = last;
      this.siftDown(0);
    }
    return top;
  }

  private siftUp(i: number): void {
    while (i > 0) {
      const parent = Math.floor((i - 1) / 2);
      if (this.compare(this.items[i], this.items[parent]) >= 0) return;
      [this.items[i], this.items[parent]] = [this.items[parent], this.items[i]];
      i = parent;
    }
  }

  private siftDown(i: number): void {
    const n = this.items.length;
    for (;;) {
      const left = 2 * i + 1;
      const right = left + 1;
      let smallest = i;
      if (left < n && this.compare(this.items[left], this.items[smallest]) < 0) smallest = left;
      if (right < n && this.compare(this.items[right], this.items[smallest]) < 0) smallest = right;
      if (smallest === i) return;
      [this.items[i], this.items[smallest]] = [this.items[smallest], this.items[i]];
      i = smallest;
    }
  }

  toArray(): T[] {
    return [...this.items];
  }
}

export function demo(): string[] {
  const heap = new BinaryHeap<number>();
  for (const n of [42, 17, 8, 23, 5, 31, 12]) heap.push(n);
  const lines = [`heap array: [${heap.toArray().join(", ")}], min = ${heap.peek()}`];
  lines.push(`pop: ${heap.pop()}, ${heap.pop()} → [${heap.toArray().join(", ")}]`);

  // A priority queue of tasks: lower number = more urgent.
  type Task = { name: string; priority: number };
  const tasks = new BinaryHeap<Task>((a, b) => a.priority - b.priority);
  tasks.push({ name: "write docs", priority: 3 });
  tasks.push({ name: "fix outage", priority: 1 });
  tasks.push({ name: "review PR", priority: 2 });
  const order: string[] = [];
  while (tasks.size) order.push(tasks.pop()!.name);
  lines.push(`tasks in priority order: ${order.join(" → ")}`);
  return lines;
}

When to use it

Use it when

  • You repeatedly need the smallest or largest item: task schedulers, event simulation, rate limiters.
  • Graph algorithms such as Dijkstra's shortest path and Prim's minimum spanning tree.
  • Finding the top k items in a stream, by keeping a heap of size k.
  • Merging k sorted lists, by keeping the head of each list in a heap.

Avoid it when

  • You need to search for arbitrary items, or iterate in sorted order. Use a balanced search tree.
  • You only ever need the minimum once: a single linear scan is simpler.
  • Priorities change often for items already in the heap and you have no index to find them. Use an indexed heap or a different structure.

Pitfalls

  • Off-by-one index math. With zero-based arrays, children are at 2i + 1 and 2i + 2; mixing in one-based formulas breaks the heap silently.
  • Assuming the array is sorted. Only the root is guaranteed to be the minimum.
  • Mutating priorities in place. Changing an item's priority without re-sifting breaks the heap property.
  • Forgetting ties. A heap isn't stable: items with equal priority come out in no particular order unless you add a tie-breaker such as an insertion counter.

Alternatives

Balanced search tree

Choose it when you also need ordered iteration, search, or to remove arbitrary items in O(log n).

Sorted array

Choose it when the data is mostly static and you need all items in order.

Heapsort

Choose it when you want to sort in place with guaranteed O(n log n) time, using the same idea.