Skip to content
jshacks.dev
Fundamentals

Implement a priority queue with a binary heap

Implement a priority queue in JavaScript with a binary heap, so push and pop take logarithmic time, with a comparator for any item shape.

2 min read
Summarize in AI

Task schedulers and shortest-path searches need the smallest item next. Sorting after every insert is wasteful. A binary heap stored in an array keeps the smallest item at index 0.

JavaScript
class PriorityQueue {
  #heap = [];

  constructor(compare = (a, b) => a - b) {
    this.compare = compare;
  }

  push(value) {
    const heap = this.#heap;
    heap.push(value);
    let i = heap.length - 1;
    while (i > 0) {
      const parent = (i - 1) >> 1;
      if (this.compare(heap[i], heap[parent]) >= 0) break;
      [heap[i], heap[parent]] = [heap[parent], heap[i]];
      i = parent;
    }
  }

  pop() {
    const heap = this.#heap;
    if (heap.length === 0) return undefined;
    const top = heap[0];
    const last = heap.pop();
    if (heap.length > 0) {
      heap[0] = last;
      let i = 0;
      for (;;) {
        const left = 2 * i + 1;
        const right = left + 1;
        let smallest = i;
        if (left < heap.length && this.compare(heap[left], heap[smallest]) < 0) smallest = left;
        if (right < heap.length && this.compare(heap[right], heap[smallest]) < 0) smallest = right;
        if (smallest === i) break;
        [heap[i], heap[smallest]] = [heap[smallest], heap[i]];
        i = smallest;
      }
    }
    return top;
  }
}

const queue = new PriorityQueue((a, b) => a.priority - b.priority);
queue.push({ task: 'deploy', priority: 3 });
queue.push({ task: 'fix', priority: 1 });
queue.push({ task: 'review', priority: 2 });
console.log(queue.pop().task, queue.pop().task, queue.pop().task);
Text
fix review deploy

A parent sits at index (i - 1) >> 1 and its children at 2i + 1 and 2i + 2, so the tree needs no pointers. push moves the new item up, and pop moves the replacement down, each in a number of steps proportional to the height of the tree.

Items with equal priority come out in no guaranteed order. If you need first in, first out among equals, add a counter to the comparison.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.