norders n!min heighta5b9c2a ≤ b?b ≤ c?a ≤ c?a ≤ c?1def sort3(a, b, c):2 if a <= b:3 if b <= c: return a, b, c4 if a <= c: return a, c, b5 return c, a, b6 if a <= c: return b, a, c7 if b <= c: return b, c, a8 return c, b, ab ≤ c?a b ca c bc a bb a cb c ac b ayesnoyesnoyesnoyesnoyesno5 9 2
Question blocks: one comparison, a yes branch and a no branchLeaf blocks: one sorted order of a, b, cThe hopping card: the input 5, 9, 2 being sortedsort3 asks yes-or-no questions; drawn as a tree, each question is a block and each answer a leaf. Three items can arrive in 3! = 6 orders, each needing its own leaf, and a tree of height 2 has room for only 4: some input needs 3 comparisons. For n items the tree needs 2ʰ ≥ n!, so h ≥ log₂(n!), which grows like n log n.

One question at a time

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

The decision tree

From three items to n

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.