Heap Sort
Sorting O(n log n) O(1)Builds a max-heap, then repeatedly swaps the root to the end and re-heapifies the shrinking prefix.
23
7
41
15
3
34
9
28
Starting Heap Sort on 8 elements.
InvariantEvery subtree below the current index already satisfies the heap property, so sifting one node down is enough.
1/61
comparisons0swaps0size8i0largest0
heap-sort.c
void heapify(int arr[], int n, int i) {int largest = i;int l = 2 * i + 1, r = 2 * i + 2;if (l < n && arr[l] > arr[largest]) largest = l;if (r < n && arr[r] > arr[largest]) largest = r;if (largest != i) {int tmp = arr[i];arr[i] = arr[largest];arr[largest] = tmp;heapify(arr, n, largest);}}void heapSort(int arr[], int n) {for (int i = n / 2 - 1; i >= 0; i--)heapify(arr, n, i);for (int i = n - 1; i > 0; i--) {int tmp = arr[0];arr[0] = arr[i];arr[i] = tmp;heapify(arr, i, 0);}}
How Heap Sort works
Build a max-heap over the array, then repeatedly swap the root (maximum) with the last element and sift the new root down over the shrinking prefix.
Best case
Always O(n log n); heap build itself is only O(n).
Worst case
Still O(n log n) — no data-dependent blowup, and O(1) extra space.
When to use it
When you need guaranteed O(n log n) in place (real-time / adversarial inputs) and stability doesn't matter.