Reading preferences
Concept

Heaps and Heap Sort

Keep the largest item at a heap's root, then use that rule to sort.

heap, heap sort, priority queue, sorting

The largest card on top

A max-heap is a tree-shaped arrangement where each parent is at least as large as its children. The top item, or root, is therefore a largest item. A heap does not promise that every row is sorted.

        9
       / \
      6   8
     / \
    1   4

Here 9 is above 6 and 8; 6 is above 1 and 4. Both parent-child rules hold, even though 6 and 8 are not ordered left to right.

Why use it and where it helps

A heap supports a priority queue, which repeatedly chooses an item with the highest (or lowest) priority. A scheduling system might choose the most urgent waiting job, provided the application defines its priority and tie rules. Heap sort uses a max-heap to place the largest remaining item at the end repeatedly. Python's heapq is a min-heap, not a max-heap.

Follow heap sort

For [4, 1, 3, 2], build a max-heap, represented here as [4, 2, 3, 1]. Move the root to the end, then restore the heap in the remaining prefix.

Heap prefix after restoringFixed suffix
[4, 2, 3, 1][]
[3, 2, 1][4]
[2, 1][3, 4]
[1][2, 3, 4]

The full result is [1, 2, 3, 4]. Restoring the rule by moving a misplaced parent down is called sifting down.

See the reasoning

Follow the example one step at a time

Move the largest item from a max-heap to the fixed suffix. This is a prepared teaching demonstration, not live code execution.

Build a max-heap

heap: [4, 2, 3, 1]   fixed: []

The root 4 is the largest item; the heap is not necessarily fully sorted.

Python illustration

def heap_sort(numbers):
    items = numbers[:]

    def sift_down(root, size):
        while 2 * root + 1 < size:
            child = 2 * root + 1
            if child + 1 < size and items[child + 1] > items[child]:
                child += 1
            if items[root] >= items[child]:
                return
            items[root], items[child] = items[child], items[root]
            root = child

    for root in range(len(items) // 2 - 1, -1, -1):
        sift_down(root, len(items))
    for end in range(len(items) - 1, 0, -1):
        items[0], items[end] = items[end], items[0]
        sift_down(0, end)
    return items


print(heap_sort([4, 1, 3, 2]))
print(heap_sort([]))

Prepared output — not live execution:

[1, 2, 3, 4]
[]

In the array representation, the children of index i are 2*i + 1 and 2*i + 2 when those indices exist. The function copies its input before rearranging it.

Time, space, and common mistakes

Building a heap bottom-up takes O(n) time. Each of up to n removals restores the heap in O(log n), so heap sort takes O(n log n) time. Heap operations typically insert or remove the root in O(log n) and inspect it in O(1). This function uses O(n) extra space for its copy; the core rearrangement can be done in place with O(1) extra space. Heap sort is not generally stable.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. Which item is at the root of a max-heap?
2. Is every row in a heap necessarily sorted?
3. What does heap sort do with the largest item?
4. What does this heap sort return for an empty list?

References and further reading