Unit 1 of 8 · about 5 hours · derive, implement

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.

You'll be able to

  • 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 contractsComparison lower bounds and non-comparison assumptionsStable merge sort and divide-combine reasoning
1

Read

In this order, only the parts listed

0 of 5 done

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

    Algorithm A: insertion sort; Algorithm B: merge sort; Why the merge step gives you ; 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 sortDSA Handbook Patterns - quicksort vs mergesort vs heapsort

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

  3. Erickson Chapter 1: MergesortAlgorithms

    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 sortingAlgorithms

    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, bucketDSA Handbook - search, trees and heaps

    Three preconditions, three algorithms; Counting sort

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

2

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 gives in the best, average and worst case. The shared buffer costs extra space plus stack; the already-sorted short-circuit recovers on sorted input.
  • The lower bound counts leaves: distinct keys admit permutations, so a decision tree needs height at least , which is 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.
Common mistakes · 3
  • 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 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.
3

Try it yourself

Closed-book, before checking anything

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.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Prove that any comparison sort needs comparisons in the worst case.Answer

    Model the sort as a decision tree: each internal node is one comparison and each leaf is one output permutation. Sorting distinct keys needs at least leaves. A binary tree with leaves has height at least , so the height is at least . By Stirling, , so .

  2. 2.Why does counting sort not contradict that bound?Answer

    The bound counts comparisons on general input. Counting sort never compares keys; it indexes by key value, which needs bounded integer keys with for linear time. Change the assumption and the bound does not apply.

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

    Yes, it is Timsort and stable. Check sorted([(5, 'a'), (3, 'b'), (5, 'c')], key=lambda p: p[0]): the two 5s keep the order ('a') before ('c').

  4. 4.Why does merge sort cost even on already-sorted input without the short-circuit?Answer

    Every level still visits all elements to merge, and there are about levels regardless of order. The short-circuit only skips the merge work when the two runs are already ordered, which recovers on sorted input.

5

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 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).

You're done 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.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 7 more in the section
  • DSA Handbook - search, trees and heapsHandbook Academy · primary

    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.

  • AlgorithmsJeff Erickson · reference

    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 heapsortHandbook Academy · support

    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