Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

ALGORITHMS · 10  /  HEAP SORT

The Tournament.

Watch the explainer

Twelve numbers, no order. Run a tournament where every parent must beat its children, crown the champion at the top — then pluck it off, again and again, until the whole array falls into place. O(n log n), with no extra memory.

THE GIST · 20 SECONDS

Heap sort reads an array as a binary tree — node i's children are 2i+1 and 2i+2. Phase 1: build a max-heap so every parent outranks its kids and the biggest value sits at the root. Phase 2: swap that root maximum to the end, shrink the heap, and sift the new root down to fix it — repeat. Each sift is O(log n), done n times: O(n log n), entirely in place.

  • Max-heapevery parent ≥ its children
  • Rootindex 0 — the current max
  • Sift-downsink a node past bigger kids
  • In placeO(1) extra memory

Hit Step to make the next move — or Play and watch the heap build, then drain into sorted order.

UNDER THE HOOD

What you just played, written down

An array is a binary tree if you agree on the index math. Build it into a max-heap, then repeatedly harvest the root. Two phases, one array, no extra memory.

How heap sort thinks — four moves

  1. The array is a tree. Node i's children live at 2i+1 and 2i+2; its parent at (i−1)/2. No pointers — just arithmetic.
  2. Build a max-heap. Sift-down every internal node from the last parent up to the root. Now every parent beats its children, so the max sits at index 0.
  3. Harvest the root. Swap index 0 with the last unsorted slot — the biggest value is now in its final place. Shrink the heap by one.
  4. Restore & repeat. Sift the new root down to fix the heap, then harvest again. After n rounds the array is sorted.
WHY THE ARRAY GROWS SORTED FROM THE RIGHT

Each harvested maximum lands at the current end of the heap and is locked. So the sorted region builds up from the right edge inward, largest first — while the heap shrinks on the left.

The whole thing in code

def heap_sort(a):
    n = len(a)
    # PHASE 1 - build a max-heap, bottom-up
    for i in range(n // 2 - 1, -1, -1):
        sift_down(a, i, n)
    # PHASE 2 - harvest the root, shrink, restore
    for end in range(n - 1, 0, -1):
        a[0], a[end] = a[end], a[0]   # max to the end
        sift_down(a, 0, end)          # fix the heap

def sift_down(a, root, end):
    while 2*root + 1 < end:
        child = 2*root + 1
        if child + 1 < end and a[child+1] > a[child]:
            child += 1                # bigger child
        if a[root] >= a[child]:
            break                     # heap ok here
        a[root], a[child] = a[child], a[root]
        root = child
TIMEO(n log n)best = avg = worst
SPACEO(1)in place, no buffer
BUILDING THE HEAP IS ONLY O(n)

Sifting down looks like n·log n, but most nodes are near the bottom with almost no height to fall. The heights sum to a geometric series, so build-heap is O(n) — the log n only shows up in the harvest phase.

⚠ Not stable, poor cache locality

Equal keys can be reordered, so heap sort is not stable. And it hops all over the array following child indices, so it's less cache-friendly than quicksort — often losing in raw speed despite the same big-O.

↔ Sift-down vs sift-up

Building a heap by sift-down from the bottom is O(n); building it by inserting one-at-a-time with sift-up is O(n log n). Same heap, different cost — bottom-up wins.

★ Where heaps shine

The heap itself powers priority queues: Dijkstra, A*, event simulation, top-k / streaming medians, and Huffman coding. Heap sort is the heap used once, to sort.

The picture: a tree stored in an array

10584137 i = 0i = 2i = 6 100518243143576 first harvest: swap index 0 with index 6
The heap after the build phase on the input traced below. The tree on top and the array underneath are the same data: the children of index i sit at 2i+1 and 2i+2. Every parent is at least as large as its children, so the maximum, 10, is at index 0. The first harvest swaps it with the last slot, index 6, where it never moves again.

Worked example, step by step

Sort [4, 10, 3, 5, 1, 8, 7] ascending. Phase 1 turns the array into a max-heap by sifting down each parent from the last one (index 2) back to the root. Phase 2 repeatedly moves the root to the end of the live heap and sifts the new root down. Bold values are locked in final position. Comparisons and swaps are running totals.

StepWhat happensArrayComparesSwaps
0unordered input4, 10, 3, 5, 1, 8, 7——
1build: sift down index 2; 3 swaps with its larger child, 84, 10, 8, 5, 1, 3, 721
2build: sift down index 1; 10 already beats 5 and 1, no swap4, 10, 8, 5, 1, 3, 741
3build: sift down index 0; 4 sinks past 10, then past 510, 5, 8, 4, 1, 3, 783
4move max 10 to index 6, shrink heap to 6 items, sift down8, 5, 7, 4, 1, 3, 10115
5move max 8 to index 5, shrink heap to 5 items, sift down7, 5, 3, 4, 1, 8, 10137
6move max 7 to index 4, shrink heap to 4 items, sift down5, 4, 3, 1, 7, 8, 101610
7move max 5 to index 3, shrink heap to 3 items, sift down4, 1, 3, 5, 7, 8, 101812
8move max 4 to index 2, shrink heap to 2 items, sift down3, 1, 4, 5, 7, 8, 101913
9move max 3 to index 1, shrink heap to 1 items, sift down1, 3, 4, 5, 7, 8, 101914

Three things stand out. First, the build phase made only 8 comparisons and 3 swaps to produce a valid heap, much less than a full sort; the real work is the harvest. Second, in step 3 the value 4 sank two levels, passing 10 and then 5, which is the sift-down doing its job: a small value can fall a long way, but a large one near the top never does. Third, the locked region grows from the right and the array is sorted when the heap has shrunk to one item. The whole sort used 19 comparisons and 14 swaps for seven numbers, with no second array.

Complexity and trade-offs

CaseTimeSpaceWhy
Heap sortO(n log n) in every caseO(1)Counted on 1,024 numbers: 17,294 comparisons random, 18,060 already sorted, 16,407 reversed. Input order barely matters. Building the heap alone took 1,910 comparisons, about 2n.
Heap built by repeated insertionO(n log n) to buildO(1)Sift-up from the front. On ascending 1…1024 it made 8,204 swaps, against 1,015 for the bottom-up build.
Merge sortO(n log n) in every caseO(n)8,931 comparisons on the same random 1,024 numbers, fewer than heap sort, but it needs a second array and is stable.
Quicksort, first element as pivotO(n log n) average, O(n²) worstO(log n) typicalOn random input it made 11,807 comparisons; on already-sorted 1,024 numbers, 523,776. Heap sort has no such bad input.

Heap sort’s selling point is the guarantee: n log n with constant extra memory, whatever the input. Its costs are practical. It is not stable (equal keys can swap past each other during sift-down), and it jumps around memory following child indices, which is slow on real hardware compared with the sequential scans of quicksort and merge sort. The comparison counts above are lower for merge sort for the same reason: heap sort re-sifts a value that came from the bottom of the heap all the way back down.

Common mistakes

  • Stopping the build loop before the root

    Writing the build loop as range(n//2 - 1, 0, -1) never sifts index 0. For [1, 2, 3] that returns [2, 3, 1], not [1, 2, 3]: the heap property was never established at the root.

  • Building from the front instead of the back

    Sifting down indices 0, 1, …, n//2 - 1 fixes a parent before its children are heaps. For [1, 2, 3, 4] the result is [1, 2, 4, 3]. Build from the last parent toward the root, so every subtree below is already a heap.

  • Letting sift-down see the sorted tail

    The right child test must be child + 1 < end, where end is the shrinking heap size, not n. Comparing against an index that is already locked can pull a final value back in. For [1, 2, 3, 4, 5, 6, 7] this version returns [4, 7, 1, 5, 2, 6, 3].

  • Using a min-heap for an ascending sort

    A min-heap puts the smallest value at the root, so harvesting to the end builds a descending array: [3, 1, 2] becomes [3, 2, 1]. For ascending order, use a max-heap, or a min-heap and write from the front.

  • Expecting a stable result

    Heap sort moves the root to the end by swapping with a far-away slot, so equal keys can change relative order. If records with equal keys must keep their input order, add the original index as a tie-breaker or use a stable sort.

Where this shows up

  • A worst-case guarantee with no extra memory

    When an input can be adversarial or time limits are hard, an algorithm with no bad input is valuable. Some hybrid sorts start with a faster method and switch to heap sort if their recursion gets too deep, which caps the worst case at n log n.

  • Top-k without sorting everything

    The same sift-down machinery keeps the k largest of a stream: hold a heap of size k, compare each new item with the smallest of the k. That is O(n log k) time and O(k) space, much cheaper than sorting when k is small.

  • Partial sorts

    Stop the harvest loop after m steps and the last m slots already hold the m largest values in order. Build costs O(n), then each harvest costs O(log n).

  • Embedded and memory-bounded code

    With no recursion and no buffer, heap sort needs a handful of variables, so it suits devices where a merge buffer or a deep call stack is not available.

SOLVE IT YOURSELF

Solve it: heap sort in place

This one is yours to write — in Python or TypeScript, running for real in your browser. Build a max-heap, then harvest the root n times. Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement heap_sort(nums): return the list sorted ascending. Use a binary max-heap — build it with sift-down, then repeatedly swap the root maximum to the end and sift down to restore. Aim for O(n log n) time and in-place O(1) extra space.

HINTS — 4 IDEAS
  1. Children of i are 2*i+1 and 2*i+2; a node with a child at 2*i+1 < end is internal.
  2. sift_down(root, end): pick the larger child, swap if it beats the root, then continue from the child.
  3. Build the heap by sifting down from n//2 - 1 back to 0.
  4. Harvest: for end from n-1 down to 1, swap a[0] with a[end], then sift_down(0, end).
CPython · WebAssembly
QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. In a max-heap stored in an array, where is the maximum element?

    Answer: At index 0 (the root) — Every parent is ≥ its children, so the largest value bubbles all the way to the root at index 0. That is why heap sort can harvest the max in O(1) each round.

  2. What does sift-down do to a node that is smaller than its children?

    Answer: Swaps it with its larger child and continues sinking — Sift-down compares the node with its larger child and, if the child wins, swaps and repeats from the child position — sinking the small value until the heap property is restored, in O(log n).

  3. What is heap sort’s worst-case time and extra space?

    Answer: O(n log n) time, O(1) space — Heap sort is O(n log n) in every case and sorts in place with O(1) extra space — its edge over merge sort, which needs O(n) extra memory.

FAQ

Heap sort, answered

What is heap sort?

A comparison sort that builds the array into a max-heap (every parent ≥ its children, so the max is at index 0), then repeatedly swaps that root maximum to the end, shrinks the heap, and sifts down to restore it. It runs in O(n log n) using O(1) extra space.

What is a binary heap?

A complete binary tree packed into an array. For index i, children are at 2i+1 and 2i+2, parent at (i−1)/2. In a max-heap every parent is at least as large as its children — no pointers needed, the indices encode the tree.

What is sift-down (heapify)?

Restoring the heap at a node that may be too small: compare it with its larger child, swap if the child wins, and continue down from there until it's bigger than both children or hits a leaf. Cost is O(log n) — the tree's height.

What's the time and space complexity?

O(n log n) in best, average, and worst case, and O(1) extra space (in place). Building the heap is only O(n); the harvest phase contributes the log n.

Heap sort vs quicksort vs merge sort?

Quicksort is usually faster but has an O(n²) worst case. Merge sort is O(n log n) and stable but needs O(n) memory. Heap sort guarantees O(n log n) and sorts in place, but is not stable and less cache-friendly.

RESULT

—

Next → keep the heap around instead of sorting once, and you have a priority queue — the engine inside Dijkstra, A*, and every top-k stream.

▶  Watch it explained

Heap Sort: Time and Space Complexity, From First Principles

Finished this one? 0 / 99 Algorithms done
NextTimsort: Sort What's Already There Next on the “The comparison sorts” ladder · rung 4 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms