Lesson 51 of 86IntermediatePro Interactive Lesson

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

MetricComplexity
Time ComplexityO(n log n) worst case
Space ComplexityO(1) in-place
Topic ChapterChapter 9: Sorting & Selection
Difficulty LevelIntermediate

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.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.