All examples

Heapsort (binary heap), .

In-place heapsort - build a max-heap, then extract the max.

heapsort.js
function siftDown(heap, i, n) {
  while (true) {
    let largest = i;
    const l = 2 * i + 1;
    const r = 2 * i + 2;
    if (l < n && heap[l] > heap[largest]) largest = l;
    if (r < n && heap[r] > heap[largest]) largest = r;
    if (largest === i) return;
    [heap[i], heap[largest]] = [heap[largest], heap[i]];
    i = largest;
  }
}
function heapSort(heap) {
  const n = heap.length;
  for (let i = Math.floor(n / 2) - 1; i >= 0; i--) siftDown(heap, i, n);
  for (let end = n - 1; end > 0; end--) {
    [heap[0], heap[end]] = [heap[end], heap[0]];
    siftDown(heap, 0, end);
  }
  return heap;
}
heapSort([5, 3, 8, 1, 9, 2]);

What to watch

The heap array renders as a binary tree: sift-down swaps ripple down the tree while the backing array strip mirrors each write.

Reading heapsort (binary heap)on a page only gets you so far - code is a process, and the process happens at runtime where you can't normally see it. In NeonFlow, this exact program runs step by step: every call opens a frame, every branch picks a path, and every value moves through memory in front of you. That's the fastest way to actually understand how heapsort (binary heap) works.

Run heapsort (binary heap) yourself

Open NeonFlow, paste this code (or any of your own), and scrub through it one step at a time.

Open NeonFlow