Sub topic 14
Choosing Between Merge Sort, Quicksort, and Heapsort
This chapter assumes you know the earlier results for merge sort: O(n log n) time in every case, O(n) auxiliary space for arrays, and stability. It also assumes you know the basic idea of quicksort (partition around a pivot, then recurse) and heapsort (build a max-heap, then repeatedly extract the maximum). The goal is to compare the three algorithms on the properties that decide real choices.
The Properties Side by Side
| Property | Merge sort | Quicksort | Heapsort |
|---|---|---|---|
| Best time | O(n log n), or O(n) with the "already ordered" skip | O(n log n) | O(n log n) |
| Average time | O(n log n) | O(n log n) | O(n log n) |
| Worst time | O(n log n) | O(n²) | O(n log n) |
| Auxiliary space (arrays) | O(n) | O(log n) stack with care | O(1) |
| Stable | Yes | No (typical in-place versions) | No |
| Memory access pattern | Sequential scans | Sequential scans | Jumps across the heap |
| Works well on linked lists | Yes, O(1) extra space | Awkward | No |
| Works well on external data | Yes, k-way merge | Poorly | No |
All three run in O(n log n) on average, so the constant factors and the guarantees decide the choice.
Where Each One Wins
Quicksort: fastest in practice on arrays
Quicksort partitions in place and scans memory sequentially, so it uses the CPU cache well and does few data moves. With a randomized or median-of-three pivot, the O(n²) worst case becomes very unlikely on ordinary inputs. An adversary can still construct inputs that trigger it, however. If you recurse on the smaller partition first, the stack depth stays at O(log n).
Heapsort: guaranteed bounds with no extra memory
Heapsort is the only algorithm of the three that combines an O(n log n) worst case with O(1) extra space. Its weakness is speed. Sifting down jumps between index i and 2i + 1, which causes cache misses on large arrays, so it is usually several times slower than quicksort. It is also unstable.
Merge sort: stability and predictability
Merge sort never degrades, it is stable, and its sequential merges suit linked lists, disk files, and parallel execution. The cost is the O(n) buffer for arrays and the extra copying that buffer requires.
What Real Libraries Do
Standard libraries combine these algorithms instead of choosing one:
- Python
sortedandlist.sortuse Timsort, a merge sort hybrid that is stable and runs in O(n) on already sorted data. - Java sorts object arrays with Timsort, because stability matters for objects. It sorts primitive arrays with dual-pivot quicksort, where stability can't be observed.
- C++
std::sortuses introsort. Introsort runs quicksort and switches to heapsort when the recursion gets too deep, which caps the worst case at O(n log n).std::stable_sortuses merge sort.
Stability matters when you sort by one key after another. Each sort keeps the order set by the previous one:
records = [("bob", 25), ("amy", 30), ("cat", 25), ("dan", 30)]
by_name = sorted(records, key=lambda r: r[0])
by_age_then_name = sorted(by_name, key=lambda r: r[1])
print(by_age_then_name)
# [('bob', 25), ('cat', 25), ('amy', 30), ('dan', 30)]An unstable sort could return ('cat', 25) before ('bob', 25), which would break the name ordering inside each age group.
A Decision Guide
Exercise
You are sorting 10 million fixed-size records in a real-time embedded system. You have almost no spare RAM, every call must finish within a strict deadline, and record order among equal keys does not matter. Which algorithm fits best, and why not the other two?
Show answer
Heapsort. It guarantees O(n log n) in the worst case using O(1) extra space. Merge sort also has the time guarantee, but it needs an O(n) buffer, which the system cannot afford. Quicksort is in place and usually faster, but its O(n²) worst case could miss the deadline. Introsort would also be acceptable, because its heapsort fallback provides the same guarantee.
Exercise
Java uses Timsort for arrays of objects but quicksort for arrays of int. Explain the reasoning.
Show answer
Two equal ints can't be told apart, so stability has no visible effect, and quicksort's speed and low memory use win. Objects that compare as equal can still differ in other fields, so a stable sort is required to keep their original order, and Timsort provides that.