3.6.2 · D3Sorting & Searching

Worked examples — Merge sort — divide and conquer, O(n log n), stable, proof of correctness

2,514 words11 min readBack to topic

This page hunts down every kind of input merge sort can meet — not just the pretty ones. We start with a map of all the cases, then work each one fully so you never hit a surprise on an exam.

See the parent for the full theory: Merge sort — divide and conquer, O(n log n), stable.


The scenario matrix

Cell Case class What could go wrong / why it matters Covered by
A Empty / single element (degenerate) Base case — does recursion even stop? Ex 1
B Odd length (uneven split) mid = n//2 splits ; do we lose an element? Ex 2
C Already sorted (best-looking input) Does merge do wasted work? Is it still ? Ex 3
D Reverse sorted (worst-looking input) Every comparison "loses" — max shuffling Ex 4
E All equal / ties (stability corner) Does order of equal keys survive? Ex 5
F Duplicates + < vs <= (stability break) The one line that makes or breaks stability Ex 6
G Exact comparison count (limiting/counting) Best-case vs worst-case comparisons for fixed Ex 7
H Real-world word problem (external merge) Merging two sorted files too big for memory Ex 8
I Exam twist (count inversions via merge) Reuse the merge to solve a different problem Ex 9

Every numeric answer below is machine-checked at the bottom.


Cell A — the degenerate base cases


Cell B — odd length, uneven split

See the recursion tree for this odd split:

Figure — Merge sort — divide and conquer, O(n log n), stable, proof of correctness

Cell C — already-sorted input (does it waste work?)


Cell D — reverse-sorted input (maximum shuffling)


Cell E — all-equal keys (stability corner)


Cell F — the < vs <= stability break


Cell G — exact comparison counts (best vs worst of a single merge)


Cell H — real-world word problem (external merge)


Cell I — exam twist: count inversions using merge


Recall Quick self-test

Which cell forces <= over <? ::: Cell E/F — ties, for stability. Does already-sorted input make merge sort faster asymptotically? ::: No — best = worst = ; structure is input-independent. Fewest comparisons to merge lists of length and ? ::: (one list fully precedes the other). Most comparisons to merge lengths ? ::: . How does merge count inversions? ::: Add the number of left-half elements remaining each time you take from the right half.

Connections

  • Parent: Merge sort theory & proof
  • Divide and Conquer — the paradigm every example above rides on.
  • Stability of Sorting Algorithms — Cells E and F live here.
  • External Sorting — Cell H's real-world merge.
  • Big-O Notation · Master Theorem — where the counts become asymptotics.
  • Quick sort — contrast: not stable, not input-independent.