The whole, before the parts

Heapsort orders a collection by repeatedly selecting its largest remaining value. It organizes the unfinished portion so that the next largest value stays easy to find. Citation needed

Terminology and core concepts

A max-heap is an array representing a complete binary tree in which each parent is at least as large as its children. At index i, the children are at 2i + 1 and 2i + 2. The root is therefore the maximum. Build a heap, swap its root with the last unsorted value, shrink the heap boundary, and sift the new root downward until the heap property is restored. The sorted suffix grows from right to left. Citation needed

Learning path

Trace an example

input             [4, 1, 3, 2]
build max-heap    [4, 2, 3, 1]
extract 4         [3, 2, 1 | 4]
extract 3         [2, 1 | 3, 4]
extract 2         [1 | 2, 3, 4]
The prefix is a heap, not a sorted list; the suffix is in its final sorted order.

Implement it in Python

Read the loop alongside the trace, then run this self-contained example with Python 3. The assertions show expected results. Inputs use ordinary Python lists and dictionaries; comparisons and numeric operations are assumed to behave normally. Citation needed

def heapsort(values):
    def sift(root, end):
        while 2 * root + 1 < end:
            child = 2 * root + 1
            if child + 1 < end and values[child] < values[child + 1]:
                child += 1
            if values[root] >= values[child]:
                break
            values[root], values[child] = values[child], values[root]
            root = child

    n = len(values)
    for root in range(n // 2 - 1, -1, -1):
        sift(root, n)
    for end in range(n - 1, 0, -1):
        values[0], values[end] = values[end], values[0]
        sift(0, end)
    return values

assert heapsort([4, 1, 3, 2]) == [1, 2, 3, 4]
assert heapsort([]) == []
assert heapsort([2, 2, 1]) == [1, 2, 2]

Citation needed

Analyze the cost

Bottom-up heap construction takes O(n) because most nodes have little distance to sift. Each of n extractions costs at most O(log n), giving O(n log n) worst-case time. This iterative in-place version uses O(1) extra space. It is not stable. Citation needed

A mistake to watch for

The end boundary is exclusive. Sifting into the sorted suffix would move values already placed correctly. Citation needed

Practice and recall

  1. What is the first extraction from max-heap [9, 4, 7, 1]?

    Work it out before opening the solution. Citation needed

    Show the reasoning
    1. Swap the root 9 with the final value 1. The suffix now contains 9.
    2. Compare root 1 with children 4 and 7; swap with 7.
    3. The remaining heap is [7, 4, 1], followed by sorted suffix [9].

    Citation needed

Why is the maximum at the root of a max-heap?
Every parent is at least as large as its children. Citation needed

To check your understanding, reproduce the implementation without looking, explain why its main step is safe, and test an edge case before moving to the next algorithm. Citation needed

Sources