Quicksort vs Mergesort: Hardware, Stability and Disk Trade-offs
Heaps, Sorting & SearchModel answerLast updated
Compare two O(n log n) sorts by how they use caches, preserve tie order, resist bad inputs, and behave when data lives on disk instead of in memory.
Choosing a Sort for a Product Catalog
You are building the sorting layer of a catalog service that orders large lists of product records. Quicksort and Mergesort both run in O(n log n) time on average, yet engineers pick between them for very different reasons. Write the kind of answer you would give a senior engineer who asks you to justify the choice.
What to cover
- Cache and memory behavior. Why does Quicksort usually beat Mergesort in wall-clock time on current CPUs when sorting a contiguous array, even though both belong to the same complexity class?
- Stability. Define a stable sort. Records must be ordered by
price, and records with the same price must stay in their originaltimestamporder. Which algorithm is the safer choice, and why? Mention how you would get the right result with an unstable algorithm. - Bad inputs for Quicksort. Give input shapes that push Quicksort to O(n²). Explain how random pivot selection and the median-of-three rule reduce the risk, and what each one cannot protect against.
- Data larger than RAM. The records are stored on disk and do not fit in memory. Which algorithm would you build on, and why? Frame your reasoning in terms of sequential versus random access.
Expectations
- Tie each claim to what the hardware does (L1/L2 cache, prefetching, RAM, disk I/O).
- Do not stop at quoting O(n log n) or O(n²). Describe what the partition step and the merge step actually do to memory.
- State trade-offs and the situations where your conclusion would change.
Hints
Hint 1
Compare the memory traffic of the two inner loops: what does partitioning read and write, versus what does merging read and write at every level of recursion?
Hint 2
For stability, ask what happens to two equal keys when elements are swapped across long distances, and which side a merge should take from when keys tie. Also consider sorting by a composite key.
Hint 3
For the worst case, think about which inputs make every pivot the minimum or maximum, including inputs with many equal keys. Then ask whether a deterministic pivot rule can still be attacked.
Hint 4
For disk, count full passes over the data and check whether each pass is sequential. Think about run generation followed by a k-way merge.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Both sorts are O(n log n) on average. They differ in how they touch memory and what guarantees they offer.
- Quicksort partitions in place. It does little work per element, copies nothing, and has excellent cache behavior. It is not stable and can degrade to O(n²) with bad pivots.
- Mergesort moves data through an auxiliary buffer. It generates more memory traffic but is stable, has guaranteed O(n log n) time, and accesses data purely sequentially, which suits disk.
1. Cache and memory behavior
Quicksort's partition step
- Two indices sweep through consecutive addresses, a pattern the hardware prefetcher handles very well.
- Every comparison is against one pivot kept in a register.
- There is no auxiliary array, so the working set is just the subarray being partitioned.
- Once a subarray fits in L1/L2 (roughly 32 KB to 1 MB), all deeper recursion on it runs from cache.
- Elements move only when they are on the wrong side, which is about half of them per level on random data.
Mergesort's merge step
- It reads two runs and writes a third buffer, so roughly 2n words of traffic per level.
- Every element is copied at every one of the log n levels.
- It needs an n-sized buffer. Allocating it, especially per call, costs time and adds cache and TLB pressure.
The complexity class is the same, but the constants are not. Quicksort performs fewer writes and has a smaller footprint, so it typically wins on arrays of primitives.
Caveat for product objects. If the list holds references to heap objects, every comparison chases a pointer, which erodes Quicksort's locality advantage. This is part of why some standard libraries use a tuned Quicksort for primitive arrays but a stable merge-based sort (Timsort) for object arrays.
2. Stability
A sort is stable if records with equal keys keep their original relative order.
- Mergesort is stable provided the merge takes from the left run when keys tie (
<=, not<). Left-run items came earlier, so equal items never cross. - Quicksort is not stable. Partitioning swaps items across long distances, so two items priced 9.99 can pass each other.
For "price, then timestamp for ties":
- If the data is already in timestamp order (such as an append-only log), a single stable sort by price is enough.
- Otherwise, sort by timestamp first, then stable-sort by price. Alternatively, sort once on the composite key
(price, timestamp), which works with any algorithm, including Quicksort.
Mergesort is the safer default because correctness does not depend on someone remembering to build the composite key.
3. Worst-case behavior of Quicksort
The quadratic case arises when partitions are maximally lopsided. Each step removes one element, recursion depth reaches n, and total work is about n²/2.
Triggers
- Sorted or reverse-sorted input with a first-element or last-element pivot. Re-sorting nearly sorted inventory data is common.
- Many duplicate keys with a two-way partition, for example thousands of items at one price. All equal keys fall on one side.
- Adversarial input crafted against a known deterministic pivot rule.
Mitigations
- Median-of-three (first, middle, last) handles sorted and reverse-sorted input well. It is still deterministic, so crafted inputs can defeat it, and it does not fix duplicates.
- Random pivot makes the expected time O(n log n) for every input, because bad splits depend on random choices rather than data. The chance of quadratic behavior is negligible.
- Three-way partitioning (less, equal, greater) finishes the equal block in one pass, which resolves the duplicates problem.
- Introsort switches to heapsort when recursion depth exceeds about 2·log₂ n, giving a hard O(n log n) bound.
- Recursing into the smaller side first keeps stack depth at O(log n).
4. Data larger than RAM
Choose external Mergesort.
- Run generation. Read chunks of size M (available RAM) sequentially, sort each in memory with any fast sort, and write each sorted run sequentially.
- k-way merge. Open k runs, keep one buffered block per run plus a min-heap, and stream the merged output sequentially.
Total I/O is about 2N · ⌈log_k(N/M)⌉. With a large k this is often one or two passes, all sequential. Disks and SSDs deliver far higher throughput for sequential access than for random seeks.
A single Quicksort partition is itself two sequential scans, so the real problems are different:
- In-place swaps mean read-modify-write at two moving file positions.
- Each recursion level re-reads the data, giving about log₂(N/M) passes rather than log_k.
- Choosing a good pivot for data you have not read is hard.
Mergesort's structure maps directly onto streaming I/O.
Summary table
| Quicksort | Mergesort | |
|---|---|---|
| Time (average / worst) | O(n log n) / O(n²) | O(n log n) / O(n log n) |
| Extra space | O(log n) stack | O(n) buffer |
| Stable | No | Yes |
| Cache behavior | Excellent, in place | More traffic, sequential |
| External sorting | Poor fit | Natural fit |
Common mistakes
- Saying Quicksort is faster because of its complexity. The advantage is in constants and memory behavior.
- Using
<instead of<=on ties in the merge, which silently breaks stability. - Claiming median-of-three removes the O(n²) risk. It only helps on common patterns, and not for duplicates or adversarial input.
- Forgetting that duplicates need three-way partitioning.
- Claiming Quicksort is unsuitable on disk because partitioning is non-sequential. The real issue is the number of passes and the in-place writes.
Practical recommendation
For an in-memory array of primitives or compact keys where stability is not required, use a tuned Quicksort variant (introsort). For records where tie order matters, or when worst-case guarantees are needed, use a stable merge-based sort. For data on disk, use external Mergesort.