Sub topic 1
What a Comparison Sort Does
A sorting algorithm puts a sequence of elements into order. Most general-purpose sorts in standard libraries are comparison sorts. A comparison sort learns about the data only by asking one question about two elements at a time: "should a come before b?" This chapter explains what that restriction means, what it costs, and why it matters for the rest of the tutorial.
Prerequisites
This chapter assumes you can:
- write basic programs in at least one mainstream language
- work with arrays, lists, and records or structs
- read Big-O notation for time and space
- pass a function or lambda as an argument to another function
The only question a comparison sort asks
A comparison sort never looks inside an element to see its value. It cannot tell that 42 is "about in the middle" or that a string starts with z. It only gets yes or no answers to "is a less than b?" Every decision it makes, every swap, shift or merge, follows from those answers.
This design is what makes library sorts generic. The same function can sort integers, strings, dates, or your own records, as long as something can answer the ordering question. Later chapters cover how you supply that answer with keys and comparators.
Counting the questions
You can watch a library sort ask its questions by wrapping the comparison so that it counts calls:
from functools import cmp_to_key
import math
import random
comparisons = 0
def compare(a, b):
global comparisons
comparisons += 1
return (a > b) - (a < b) # -1, 0 or 1
data = random.sample(range(10_000), 1000)
result = sorted(data, key=cmp_to_key(compare))
print(result == sorted(data)) # True
print(comparisons, "comparisons used")
print(math.ceil(math.log2(math.factorial(1000))), "minimum in the worst case")On random input, Python's sort uses roughly 8,700 comparisons for 1,000 elements. The minimum it could guarantee is 8,530. The next section explains where that minimum comes from.
Why n log n is the floor
Each comparison has two possible answers, so any comparison sort can be drawn as a binary decision tree. Each internal node is a question, and each leaf is one final ordering. For three elements there are 3! = 6 possible orderings, so the tree needs six leaves:
A binary tree of height h has at most 2^h leaves. To distinguish n! orderings you need 2^h ≥ n!, so h ≥ log₂(n!), which grows as Θ(n log n). In the worst case, no comparison sort can do better than about n log n comparisons, however clever it is.
Common misunderstandings
| Misunderstanding | What is actually true |
|---|---|
| "A smart enough comparison sort could run in O(n)." | O(n) is impossible in the worst case. The lower bound is Ω(n log n) comparisons. Some sorts do reach O(n) on special inputs, such as data that is already sorted. |
| "Counting sort and radix sort break the lower bound." | They are not comparison sorts. They read digits or values directly, so the bound does not apply to them. They only work for suitable key types. |
| "If the comparison says two elements are equal, they are the same." | They are only equal *for ordering purposes*. Two records can tie on the compared field and still differ in other fields. |
Exercise
What is the minimum number of comparisons any comparison sort needs in the worst case to sort 4 distinct elements?
Show answer
There are 4! = 24 possible orderings, and log₂ 24 ≈ 4.58. The decision tree needs at least 24 leaves, so its height must be at least 5. The answer is 5 comparisons.
Exercise
A sort places each integer from 0 to 99 into a bucket indexed by its value and then reads the buckets in order. Is it a comparison sort, and does the n log n lower bound apply to it?
Show answer
No. It uses each value directly as an array index and never asks whether one element is less than another. The comparison lower bound does not apply, which is how it can run in O(n + k) time.