Heapsort with a Max-Heap
Move the root into the sorted suffix, then repair the remaining heap.
Core Intuition & How It Works
Heapsort builds a max-heap in place in O(n) time, then repeatedly swaps the maximum root to the end of the unsorted suffix and sifts down. It achieves guaranteed O(n log n) worst-case time using O(1) extra space.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n log n) worst case |
| Space Complexity | O(1) in-place |
| Topic Chapter | Chapter 9: Sorting & Selection |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Shrink the active heap boundary by 1 after each root-to-end swap so the sorted suffix grows from right to left.
Common Pitfalls & Edge Cases
Expecting heapsort to beat quicksort on cache-heavy workloads—its non-local tree jumps have poorer cache locality and it is unstable.
Real-World & Technical Interview Applications
Worst-case fallback inside Introsort and memory-constrained real-time systems requiring O(1) space.