Sub topic 1
What a Comparison Sort Does
Every sort function in a standard library answers one question: given a list of items, in what order should they come out? Most of them answer it the same way. They compare pairs of items and move items based on the results. This chapter explains that model, what it costs, and where it stops working. Later chapters build on it to explain stability and how real libraries sort.
Prerequisites
This chapter assumes you can already:
- Write basic programs in at least one mainstream language. The examples use Python.
- Work with arrays, lists, and records or structs.
- Read Big-O notation for time and space, such as O(n log n) and O(n).
- Pass a function or lambda as an argument to another function.
You do not need to know any sorting algorithm in detail. The algorithms that matter are introduced where they are needed.
The Output of a Sort
A sort takes a sequence of n items and returns them in a new order. The output must satisfy two conditions:
- It is ordered. Each item is not "greater" than the item after it, under whatever ordering you supplied.
- It is a permutation of the input. Every input item appears exactly once in the output. Nothing is added, dropped, or changed.
The second condition is easy to overlook. A function that returned [1, 2, 3] for every input would satisfy the first condition and fail the second. When you test a sort, check both.
Notice what the definition leaves open. If two items count as equal under the ordering, either may come first and both conditions still hold. The definition does not settle which one goes first. Chapter 3 is about that choice.
The Comparison Model
A comparison sort learns about the items only by asking questions of the form "is a less than b?" It never inspects an item's bits, digits, or characters directly. The answer to each question is true or false, and the algorithm uses these answers to decide which items to move.
This makes comparison sorts general. The same algorithm can sort integers, strings, dates, or records, as long as you can supply a rule that compares two of them. Here is a small comparison sort that takes that rule as a parameter called less:
def selection_sort(items, less):
items = list(items)
for i in range(len(items)):
smallest = i
for j in range(i + 1, len(items)):
if less(items[j], items[smallest]):
smallest = j
items[i], items[smallest] = items[smallest], items[i]
return items
words = ["pear", "Fig", "apple", "kiwi"]
print(selection_sort(words, lambda a, b: a < b))
# ['Fig', 'apple', 'kiwi', 'pear'] (uppercase letters sort before lowercase)
print(selection_sort(words, lambda a, b: a.lower() < b.lower()))
# ['apple', 'Fig', 'kiwi', 'pear']
print(selection_sort(words, lambda a, b: len(a) < len(b)))
# ['Fig', 'pear', 'kiwi', 'apple']The algorithm stays the same in all three calls, and only the less function changes. The algorithm never asks what a word is. It only acts on the true-or-false answers it gets back.
The third call is worth a second look. Under "shorter is less", pear and kiwi are equal because both have four letters. Neither less("pear", "kiwi") nor less("kiwi", "pear") is true. The algorithm put pear first, but nothing in the ordering required that. Chapter 2 covers how keys and comparators define "equal", and Chapter 3 covers what a sort should do with equal items.
Comparisons as a Decision Tree
You can picture any comparison sort, on inputs of a fixed size n, as a decision tree. Each internal node is a comparison. Each branch is one answer. Each leaf is a final ordering. Running the algorithm on a particular input means walking one path from the root to a leaf.
Here is a decision tree that sorts three distinct items a, b and c:
Three distinct items can be arranged in 3! = 6 ways, and the tree has six leaves, one per arrangement. A correct sort must be able to reach every possible arrangement, because any of them could be the right answer for some input.
The n log n Lower Bound
The decision tree gives a hard limit on how fast any comparison sort can be.
- There are n! possible orderings of n distinct items, so the tree needs at least n! leaves.
- A binary tree of height h has at most 2^h leaves.
- So 2^h ≥ n!, which means h ≥ log₂(n!).
The height h is the number of comparisons on the longest path, which is the worst case. Using Stirling's approximation, log₂(n!) is about n log₂ n − 1.44n. In Big-O terms, every comparison sort needs Ω(n log n) comparisons in the worst case. The same bound holds for the average case over random inputs.
This limit applies to every possible comparison sort, including ones nobody has invented yet. Merge sort, heapsort, Timsort and introsort all reach O(n log n) in the worst case. They differ in constant factors, memory use, behaviour on partly sorted data, and whether equal items keep their input order.
Measuring Comparisons in Practice
You can count the comparisons a real library sort makes by wrapping the comparison in a counter. Python's functools.cmp_to_key turns a three-way comparison function into a key that sorted accepts:
import math
import random
from functools import cmp_to_key
def count_comparisons(data):
count = 0
def compare(a, b):
nonlocal count
count += 1
return (a > b) - (a < b) # -1, 0 or 1
result = sorted(data, key=cmp_to_key(compare))
return result, count
for n in (10, 100, 1000, 10000):
data = [random.random() for _ in range(n)]
result, count = count_comparisons(data)
assert result == sorted(data)
lower = math.lgamma(n + 1) / math.log(2) # log2(n!)
print(f"n={n:>6} comparisons={count:>7} "
f"log2(n!)={lower:>9.0f} n*log2(n)={n * math.log2(n):>9.0f}")The exact counts change from run to run because the data is random. For random input you should see the comparison count stay a little above log₂(n!) and below n log₂ n. Now replace the random data with list(range(n)) and run it again. The count drops to n − 1. The lower bound is still true, because it describes the worst case and an already-sorted list is far from the worst case.
Sorting Without Comparisons
The n log n limit applies only to algorithms that learn about the input through comparisons. If you know more about the keys, you can skip comparisons altogether. Counting sort handles small non-negative integers by counting how many times each value appears:
def counting_sort(values, max_value):
counts = [0] * (max_value + 1)
for v in values:
counts[v] += 1
result = []
for v, c in enumerate(counts):
result.extend([v] * c)
return result
print(counting_sort([3, 1, 4, 1, 5, 2], 5)) # [1, 1, 2, 3, 4, 5]This runs in O(n + k) time, where k is the range of values. Radix sort extends the idea to larger integers and fixed-length strings by processing one digit or byte at a time.
| Property | Comparison sort | Counting or radix sort |
|---|---|---|
| Learns about items by | Asking "is a < b?" | Reading digits, bytes or integer values |
| Works on | Anything with an ordering rule | Integers, fixed-width keys, short strings |
| Worst-case time | Ω(n log n) for any algorithm | O(n + k) or O(d · (n + k)) |
| Custom ordering (for example case-insensitive, by length) | Change the comparator | Must re-encode keys to fit the scheme |
| Used by default in standard libraries | Yes | Rarely, and only for special cases |
Standard libraries default to comparison sorts because they must work on any type with any user-supplied ordering. The rest of this tutorial is about comparison sorts.
Where Sorts Differ
Every comparison sort runs into the same lower bound. Three properties separate one from another, and these are the properties you choose between when you pick a library function:
- Extra memory. An in-place sort uses O(1) or O(log n) extra space and rearranges the input directly. Other sorts need an O(n) buffer. In Python,
list.sort()rearranges the list itself andsorted()returns a new list. Both use the same algorithm internally. - Adaptivity. An adaptive sort runs faster on input that is already partly ordered, as the n − 1 result above showed.
- Stability. A stable sort keeps equal items in their input order. This is the main subject of the tutorial, and Chapter 3 defines it precisely.
Exercises
Exercise
What is the smallest worst-case number of comparisons any comparison sort can guarantee for 4 distinct items?
Show answer
There are 4! = 24 orderings, so the decision tree needs at least 24 leaves. 2^4 = 16 is too few and 2^5 = 32 is enough, so at least 5 comparisons are needed in the worst case. log2(24) is about 4.58, which rounds up to 5.
Exercise
You need to sort a list of strings case-insensitively, and then by length. Why is a comparison sort a better fit than counting sort?
Show answer
Counting sort needs keys that map directly to a small integer range. Arbitrary strings with a custom ordering do not fit that. A comparison sort only needs a less-than function, so you can change the ordering by passing a different comparator or key without changing the algorithm.
Exercise
A function returns sorted output but sometimes drops duplicate values. Which condition of a correct sort does it break, and how would you test for it?
Show answer
It breaks the permutation condition, because every input item must appear exactly once in the output. To test for it, compare item counts between input and output, for example collections.Counter(input) == collections.Counter(output) in Python, as well as checking that the output is ordered.
Exercise
In the selection_sort example sorted by length, pear came before kiwi. Is that output correct according to the two conditions of a sort? Would kiwi before pear also be correct?
Show answer
Yes, it is correct. Both words have length 4, so neither is less than the other, and the output is ordered and is a permutation of the input. kiwi before pear would also be correct. The definition of sorting does not choose between equal items. Stability, covered in Chapter 3, is the extra rule that does.