One question at a time
A comparison sort learns about its items in only one way: it asks “is x ≤ y?” and gets yes or no. Insertion sort, merge sort, quicksort and Python's sorted work like this. Our input: a = 5, b = 9, c = 2.
This Python function sorts exactly three items. Each if asks one question. Each return is one answer: the three items in sorted order. It asks the same questions, in the same order, as insertion sort does on three items.
Every run starts at the same top question, line 2: is a ≤ b? Here 5 ≤ 9, so the answer is yes and the run follows the yes branch. The input card hops onto the first question.
Line 3 asks b ≤ c: 9 ≤ 2 is no. Line 4 asks a ≤ c: 5 ≤ 2 is no. Line 5 is a leaf: return c, a, b, which is 2, 5, 9. Three questions sorted this input.
The decision tree
Each input follows one path like this. Draw all the paths at once and you get a decision tree: 5 questions and 6 leaves. Its height, the longest path from the top to a leaf, is the worst-case number of comparisons: 3.
Three different items can arrive in 3! = 3 × 2 × 1 = 6 orders. Each order needs its own leaf. If two orders reached the same leaf, the sort would rearrange both the same way, and one would come out wrong.
Each question splits a path in two, so a tree of height h has at most 2ʰ leaves. Height 2 gives at most 4, fewer than 6. So every comparison sort needs 3 questions for some order of three items.
From three items to n
The same count works for any n. n items have n! orders, so the tree needs 2ʰ ≥ n!, which means h ≥ log₂(n!). Four items need at least 5 comparisons; ten items need at least 22.
At least n/2 of the factors in n! are n/2 or more, so log₂(n!) ≥ (n/2)·log₂(n/2), which grows like n log n. So every comparison sort takes Ω(n log n) comparisons in the worst case (Ω: at least, up to a constant).
Merge sort and heapsort use O(n log n) comparisons, so they match this floor: no comparison sort beats them by more than a constant factor. Counting sort and radix sort escape it because they never compare two items; they use values as positions.
What happens
;; step 1/10 · only-compare comparison model: the only way to learn about the items ask x <= y ? -> yes / no input: a = 5, b = 9, c = 2 goal: return the three values in sorted order
The tree drawn here is the decision tree of insertion sort on three items, as in CLRS Figure 8.1. Any comparison sort has a tree like it, possibly with different questions. The bound counts comparisons only. A comparison sort also moves items, so its running time is at least its number of comparisons: Ω(n log n) time as well. The argument assumes distinct items; they are possible inputs, so the worst case can never be smaller.