7 routes42 sections324 units

Unit 2.1 · about 5 h

96 / 324

Sorting contracts, lower bounds and merge sort

Sorting is the first place an ordering invariant pays off, and the lower bound tells you when to stop tuning comparisons and change the input assumptions instead.

  • derive
  • implement

You can now

  • State the sorting contract (stability, in-place behavior, comparator rules) and pick merge sort, quicksort or heap sort from the binding constraint.
  • Prove the comparison-sorting lower bound with a decision-tree argument and explain why counting and radix sorts escape it.
  • Implement stable top-down merge sort with a shared auxiliary buffer and check it against sorted with randomized differential tests.

Covers

  • Sorting stability, in-place behavior and comparator contracts
  • Comparison lower bounds and non-comparison assumptions
  • Stable merge sort and divide-combine reasoning

Study, in this order

5 steps

  1. Comparison sorts I: insertion sort and merge sort
    DSA Handbook - search, trees and heaps

    Algorithm A: insertion sort; Algorithm B: merge sort; Why the merge step gives you \(\Theta(n \log n)\); The stability table; Worked example: merge sort on [5, 2, 4, 7, 1, 3, 2, 6]; Pitfalls

  2. Quicksort vs mergesort vs heapsort, picking your sort
    DSA Handbook Patterns - quicksort vs mergesort vs heapsort

    The decision; Algorithms compared; Side-by-side; Common misconceptions

  3. Erickson Chapter 1: Mergesort
    Algorithms

    Section 1.4 Mergesort (pp. 26 to 28), including Lemma 1.1 (Merge), Theorem 1.2 (MergeSort) and the recurrence analysis

  4. Lecture Note 12: Lower Bounds, decision trees and sorting
    Algorithms

    Sections 12.2 Decision Trees, 12.3 Information Theory, 12.4 But wait a second... and 12.5 Sorting

  5. Linear-time sorts: counting, radix, bucket
    DSA Handbook - search, trees and heaps

    Three preconditions, three algorithms; Counting sort

    Depth · Skim LSD radix sort and Bucket sort for their preconditions only (fixed-width keys; near-uniform keys). Only counting sort is implemented here.

Focus on

  • Stability means equal keys keep their input order. Merge sort is stable because the merge emits the left run on ties (<=, not <). Quicksort and heap sort are not stable.
  • The merge recurrence \(T(n) = 2T(n/2) + \Theta(n)\) gives \(\Theta(n \log n)\) in the best, average and worst case. The shared buffer costs \(\Theta(n)\) extra space plus \(\Theta(\log n)\) stack; the already-sorted short-circuit recovers \(\Theta(n)\) on sorted input.
  • The lower bound counts leaves: \(n\) distinct keys admit \(n!\) permutations, so a decision tree needs height at least \(\lg(n!)\), which is \(\Omega(n \log n)\) by Stirling. It binds only comparison sorts on general input; counting sort never compares and needs bounded integer keys instead.
  • Equal asymptotics do not mean equal speed in Python. On a 12th Gen Intel Core i9-12900K with Python 3.13.14, a pure-Python merge sort on 20,000 random ints took 0.018 s against 0.0017 s for list.sort, about 10x. State the CPU and version with every timing you report.

Reproduce closed-book

From a blank file, implement top-down merge sort with one shared auxiliary buffer, midpoint lo + (hi - lo)//2, <= in the merge, and the already-sorted short-circuit. On [5, 2, 4, 7, 1, 3, 2, 6] it must return [1, 2, 2, 3, 4, 5, 6, 7]. Stability check: [(5, 'a'), (3, 'b'), (5, 'c')] must come back [(3, 'b'), (5, 'a'), (5, 'c')]. Then run a Hypothesis differential test against sorted on 300 lists up to length 60 with seed 0.

Traps

  • Using < instead of <= in the merge. Ties taken from the right run break stability silently while every sortedness test still passes.
  • Allocating a fresh auxiliary list in every merge call. Allocate once at the top; per-call allocation adds a hidden linear factor at each of the \(\log n\) levels.
  • Reading the lower bound as a ban on fast sorting. It bans fast comparison sorting on general input; bounded keys (counting) or fixed-width keys (radix) change the model and the bound does not apply.

Practice

LeetCode 912: Sort an Array

Solve with your merge sort; example inputs [5,2,3,1] and [5,1,1,2,0,0]

Attempt before reading solutions. After submitting, read the AlgoMaster write-up for Sort an Array (https://algomaster.io/learn/dsa/sort-an-array) and compare its approach with yours.

LeetCode 88: Merge Sorted Array

Merge in place from the end with \(O(1)\) extra space; example inputs ([1,2,3,0,0,0], 3, [2,5,6], 3) and ([0], 0, [1], 1)

This is the merge step under a no-buffer constraint. After submitting, read the AlgoMaster write-up for Merge Sorted Array (https://algomaster.io/learn/dsa/merge-sorted-array).

Self-test

  1. Prove that any comparison sort needs \(\Omega(n \log n)\) comparisons in the worst case.

  2. Why does counting sort not contradict that bound?

  3. Is Python's list.sort stable, and how do you check from a REPL?

  4. Why does merge sort cost \(\Theta(n \log n)\) even on already-sorted input without the short-circuit?

Completion criterion

Stop when

Your merge sort returns the sorted handbook example, keeps equal-key order, passes 300 Hypothesis cases against sorted, and you can state the decision-tree bound and the counting-sort precondition without notes.

Mark passed, then open 2.2 Only mark this when you can do it without notes.

Leads to

Resources for this unit

  • DSA Handbook - search, trees and heaps
    Handbook Academyprimarycourse
    Study Part 2 Search and Sort, Part 5 Linked Lists, and Part 6 Trees and Heaps. Include canonical and answer-space binary search, comparison and linear-time sorts, quickselect, sentinels, cycles, heaps, BSTs, balanced-tree vocabulary, tries and segment trees.
  • Algorithms
    Jeff Ericksonreferencetheory
    Use Chapter 1 (mergesort, quicksort, recursion trees and linear-time selection) when deriving merge, partition and selection algorithms, and lecture note 12 Lower Bounds for the comparison-sorting decision-tree argument. This is the proof reference when the handbook explanation is too brief.
  • DSA Handbook Patterns - quicksort vs mergesort vs heapsort
    Handbook Academysupportsupport
    Use The decision, Algorithms compared and Side-by-side to pick a comparison sort from the binding constraint; problem details stay with their units.

Also in this section

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels