KatInterview

Quicksort vs Mergesort: Hardware, Stability and Disk Trade-offs

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchquicksortmergesortstability

Last 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

  1. 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?
  2. Stability. Define a stable sort. Records must be ordered by price, and records with the same price must stay in their original timestamp order. Which algorithm is the safer choice, and why? Mention how you would get the right result with an unstable algorithm.
  3. 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.
  4. 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.