Heap Sort, explained step by step
Heap Sort first arranges the array into a max-heap — a binary tree stored in the array where every parent is at least as large as its children. It then repeatedly swaps the root (the maximum) to the end and restores the heap on the remaining elements.
Intuition: A tournament: the champion is at the top; remove them, replay the bracket, and the next champion rises.
How it works
- Build a max-heap by heapifying every parent from the last one up to the root.
- Swap the root (maximum) with the last element of the heap.
- Shrink the heap by one and heapify the root again.
- Repeat until the heap has one element.
Complexity
- Best: O(n log n)
- Average: O(n log n)
- Worst: O(n log n)
- Space: O(1)
- Stable: no
When to use it
When you need guaranteed O(n log n) with O(1) extra memory — e.g. embedded or real-time systems.
Interview questions
- Why is building a heap O(n) rather than O(n log n)?
- Why is Heap Sort usually slower than Quick Sort in practice?
- How are the children of index i located in an array-based heap?