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.
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:
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:
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.
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.
The array in main() changes to match what you sort.
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.
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.
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.
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.
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.