Data Structures · Sorting

Heap Sort

🔢 The array a[] and the heap tree (index k ↔ node k)

node inside the heapnode sifting down / its childrenbeing swappedsettled (at the end)
result

🧾 Phase statistics

💬 Current step

💻 The algorithm (courseware-style C++)

Yellow = the line being executed. The recipe: build the heap (sift down bottom-up) → swap the root to the end → shrink the heap → sift the root down again → repeat.

📄 Key points

1Build: sift down every node from n/2 − 1 backwards
2Extract: swap(a[0], a[end]) → the maximum is settled
3Shrink the heap by one and sift the new root down
4Always O(n log n), O(1) space, but not stable
The array is the tree: index k has left child 2k+1, right child 2k+2 and parent (k−1)/2 — no pointers needed, the indices do the work.
Why is building O(n)? Most nodes sit near the bottom where the sift distance is tiny (leaves travel 0 levels, the level above at most 1, …); the sum works out to O(n), not O(n log n).
The sorting phase: n−1 rounds of “extract + sift down”, each O(log n) → O(n log n) regardless of the input order.
Versus others: quicksort is faster on average but O(n²) in the worst case; merge sort is also O(n log n) but needs O(n) extra space; heap sort is the one that is always O(n log n) with O(1) space. It shines for Top-K, priority queues and anything needing a worst-case guarantee.
Max-heap ↔ ascending: for ascending output you want a max-heap (each round throws the maximum to the end).
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result