DSA Notes
Master heap sort completely — how heapify works, building a max-heap in O(n), the two-phase sorting process, why heap sort is O(n log n) in all cases with O(1) space, the weak cache performance trade-off, and comparison with merge sort and quick sort.
What Makes Heap Sort Special?
Heap sort combines the best properties of the two sorting extremes:
- Merge Sort: Guaranteed O(n log n) worst case
- Selection Sort: O(1) auxiliary space
Heap sort achieves both simultaneously. It is:
- Always O(n log n) — no bad input exists
- In-place — only O(1) extra memory
- Not stable — equal elements may change order
The Heapify Operation
heapify(arr, n, i) — restores the max-heap property for the subtree rooted at index i, assuming both children are already valid heaps.
Building a Max-Heap in O(n)
Starting from the last non-leaf node (index n//2 - 1) and going up to the root, call heapify on each node.
def build_max_heap(arr):
"""
Build max-heap from unsorted array.
Time: O(n) — counterintuitively faster than O(n log n)
"""
n = len(arr)
# Start from last non-leaf, work toward root
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)Why O(n) and not O(n log n)?
At level h from bottom, nodes have subtrees of height h and require O(h) heapify work. There are ≤ n/2^(h+1) nodes at height h.
Total work = Σ (n/2^(h+1)) × O(h) for h=0 to log n = O(n × Σ h/2^h) = O(n × 2) = O(n) (geometric series: Σ h/2^h = 2)
The Complete Heap Sort Algorithm
Phase 2 trace:
| Max-heap | [13, 12, 7, 5, 6, 11] |
| Step 1: Swap arr[0]=13 with arr[5]=11 | [11,12,7,5,6,13] |
| Heapify [0..4] | [12,11,7,5,6] | 13 |
| Step 2: Swap arr[0]=12 with arr[4]=6 | [6,11,7,5,12] | 13 |
| Heapify [0..3] | [11,6,7,5] | 12,13 |
| Step 3: Swap arr[0]=11 with arr[3]=5 | [5,6,7,11] | 12,13 |
| Heapify [0..2] | [7,6,5] | 11,12,13 |
| Step 4: Swap arr[0]=7 with arr[2]=5 | [5,6,7] | 11,12,13 |
| Heapify [0..1] | [6,5] | 7,11,12,13 |
| Step 5: Swap arr[0]=6 with arr[1]=5 | [5,6] | 7,11,12,13 |
| Final | [5, 6, 7, 11, 12, 13] ✓ |
Complexity Analysis
Time — O(n log n) All Cases
- Phase 1 (build heap): O(n)
- Phase 2 (n-1 extractions × O(log n) heapify each): O(n log n)
- Total: O(n + n log n) = O(n log n)
Critical property: No bad input exists. Heapify always takes O(log n). Unlike Quick Sort, there is no degenerate case.
Space — O(1)
Everything happens in-place within the original array. The heap structure is implicit in the array indices — no separate heap data structure is allocated.
The recursive heapify uses O(log n) call stack, but this can be converted to an iterative loop:
Why Heap Sort is Not Used in Practice
Despite its impressive theoretical properties, Heap Sort is rarely used in practice:
Poor Cache Performance
Heap operations access memory in a non-sequential pattern
heapify at root (index 0) accesses:
index 0 → children at 1, 2
index 1 → children at 3, 4
index 3 → children at 7, 8
...
These jump around in memory → cache misses on every access
Compare with Quick Sort
Partition: sequential scan from left and right → cache hits
For large arrays on modern hardware, Heap Sort is 2-5x slower than Quick Sort despite the same O(n log n) asymptotic complexity.
Unstable
Heap Sort does not preserve the relative order of equal elements.
Comparison of O(n log n) Sorts
| Property | Merge Sort | Quick Sort | Heap Sort |
|---|---|---|---|
| Worst case | O(n log n) ✅ | O(n²) ❌ | O(n log n) ✅ |
| Average case | O(n log n) | O(n log n) | O(n log n) |
| Space | O(n) ❌ | O(log n) | O(1) ✅ |
| Stable | ✅ Yes | ❌ No | ❌ No |
| Cache friendly | Medium | ✅ Yes | ❌ Poor |
| Adaptive | ❌ No | ❌ No | ❌ No |
| Practical speed | Good | Best | Worst |
Heap Sort's niche: When both O(n log n) guarantee AND O(1) space are simultaneously required — a rare but real constraint in embedded systems and real-time applications.
Summary
Heap sort: build a max-heap, then repeatedly extract the maximum.
- Always O(n log n) — no bad input
- O(1) space — completely in-place
- Not stable — equal elements may reorder
- Poor cache performance — non-sequential memory access
- Best used when: Both worst-case guarantee AND minimal memory are required simultaneously
*Next Lesson: Counting Sort*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Heap Sort — Guaranteed O(n log n) with O(1) Space.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, sorting, heap, sort
Related Data Structures & Algorithms Topics