Data Structures · Sorting

Heap sort

Heap sort turns the array into a max-heap, so the largest value is always at the front, then repeatedly moves that largest value to the end and repairs the heap. It is selection sort with a much faster way to find the maximum, and it sorts in O(n log n) time with no extra memory.

The idea

A max-heap is a complete binary tree in which every parent is at least as large as its children. So the largest value is always at the root. The tree is stored in the array itself, level by level, exactly as on the priority queue page:

children of index i: 2i + 1 and 2i + 2    parent of index i: (i − 1) / 2

The one tool heap sort needs is heapify(arr, n, i): if the value at index i is smaller than one of its children, swap it with the larger child, and keep sifting it down until it is larger than both children (or has none). Only the first n elements count as the heap.

Heap sort then works in two phases:

  1. Build a max-heap. Call heapify on every parent, starting from the last one, index n/2 − 1, and working back to the root. Leaves are already tiny heaps, so they need no work.
  2. Extract the maximum, over and over. Swap the root (the largest value) with the last element of the heap. That value is now in its final place, so the heap shrinks by one. The new root is probably too small, so heapify it to repair the heap. Repeat until the heap has one element.

The array ends up split in two: the heap on the left, shrinking, and the sorted values on the right, growing. That is the mirror image of selection sort, which grows its sorted part from the left by finding minimums.

A worked example

Sorting {12, 11, 13, 5, 6, 7}. Blue cells are in their final sorted place; the yellow cell is the maximum that was just moved to the end.

Try it

The heap Ready

In the heap Being compared Largest of the three Sorted (out of the heap)

Variables

What is happening

main.cpp

    The array in main() changes to match what you sort.

    How much work does it do?

    Building the heap is O(n). It looks like n/2 calls to heapify at O(log n) each, but most of those calls are near the bottom of the tree, where there is almost nowhere to sift down. Half the nodes are leaves and need no work, a quarter can move down one level, an eighth two levels, and so on. The total is less than 2n swaps.

    Extracting is O(n log n). There are n − 1 extractions, and each heapify from the root moves down at most log₂ n levels, with two comparisons per level.

    So heap sort is O(n log n) in every case: best, average and worst. Unlike quicksort, it has no bad inputs. It uses only a few extra variables, so it needs O(1) extra memory and sorts in place.

    Comparisons and swaps counted by running the code above on three kinds of input:

    For comparison, selection sort always makes n(n − 1)/2 comparisons: 45, 4,950 and 499,500.

    Strengths and weaknesses

    Strengths
    • O(n log n) in the worst case, guaranteed.
    • Sorts in place with O(1) extra memory, unlike merge sort.
    • The heap is useful on its own: it is the standard way to build a priority queue.
    Weaknesses
    • Not stable: the long jumps to the end can reorder equal values. Try the Equal values preset.
    • Usually slower than quicksort in practice, because it jumps around the array and makes poor use of the CPU cache.
    • Not adaptive: sorted input still costs O(n log n).

    Think first

    After phase 1 builds the heap, where is the largest value, and how do you know?

    At index 0, the root. In a max-heap every parent is at least as large as its children, so following parents upward from any value leads to something at least as large, ending at the root.

    Why does phase 1 start at index n/2 − 1 instead of at index n − 1?

    Indexes n/2 to n − 1 are leaves: their children would be at 2i + 1 ≥ n, outside the array. A single leaf is already a heap, so heapify has nothing to do there. n/2 − 1 is the last node with a child.

    How is heap sort like selection sort? How is it different?

    Both repeatedly pick the extreme remaining value and move it into its final place. Selection sort finds the minimum by scanning the whole unsorted part, which is O(n) per pass and O(n²) in total. Heap sort keeps the unsorted part as a heap, so the maximum is always at the root and repairing the heap costs only O(log n) per pass.

    Why is heap sort not stable?

    Swapping the root with the last heap element moves a value across the whole array, past others that may be equal to it. In 5a, 5b, 3 the first extraction sends 5a to the end, so the result is 3, 5b, 5a.