Sorting and Selection: What This Course Covers
Sorting is the most studied problem in algorithm design, and for good reason. Half of all "clever" algorithms start by sorting something: binary search, finding duplicates, merging intervals, building an index, computing a median. This course takes sorting apart with the tools from Foundations of Algorithm Analysis: every algorithm gets a correctness argument, an exact or asymptotic cost, and a runnable program that counts its operations so the claims can be checked.
The course also asks the reverse question. If comparisons is what the good sorts need, is that the best possible? The answer is yes for algorithms that only compare, and no for algorithms that look at the digits of the keys. And when you only need the median, or the 10th smallest value, sorting turns out to be overkill: selection can be done in linear time.
The sorting problem, restated
The precise statement comes from Loop Invariants and the Correctness of Insertion Sort:
- Input: a sequence of keys from a totally ordered set.
- Output: a permutation of the input with .
In practice the keys travel with satellite data: you sort employee records by salary, not bare salaries. Two properties of a sorting algorithm then matter beyond its running time.
- A sort is in place if it uses only memory besides the array (some authors allow for a recursion stack).
- A sort is stable if records with equal keys come out in the order they went in.
Stability sounds cosmetic, but radix sort, the fastest sort in this course for fixed-width integers, depends on it completely. The example below sorts records by one field and shows Python's built-in sort keeping equal keys in their input order.
people = [("Ana", 31), ("Bo", 25), ("Cy", 31), ("Di", 25), ("Ed", 40), ("Fay", 31)]
by_age = sorted(people, key=lambda p: p[1]) # Python's sort is stable
for name, age in by_age:
print(age, name)
# stability lets you sort by several keys: least important key first
by_age_then_name = sorted(sorted(people, key=lambda p: p[0]), key=lambda p: p[1])
print([name for name, _ in by_age_then_name])25 Bo
25 Di
31 Ana
31 Cy
31 Fay
40 Ed
['Bo', 'Di', 'Ana', 'Cy', 'Fay', 'Ed']
Among the 31-year-olds, Ana, Cy and Fay appear in their original order. The second line is the trick behind radix sort in miniature: sort by the secondary key, then stably by the primary key.
Counting comparisons instead of seconds
Like the foundations course, this one measures cost by counting basic operations rather than timing, because counts are exact and repeatable (The RAM Model). For comparison sorts the natural operation is one key comparison. Python makes counting easy: wrap each key in an object whose < operator increments a counter. Python's sorted uses only <, so this counts every comparison it makes.
import math, random
class Counted:
count = 0
def __init__(self, v):
self.v = v
def __lt__(self, other):
Counted.count += 1
return self.v < other.v
rng = random.Random(1)
for n in [100, 1000, 10000]:
data = [Counted(rng.random()) for _ in range(n)]
Counted.count = 0
sorted(data)
lg_fact = math.lgamma(n + 1) / math.log(2) # lg(n!)
print(f"n = {n:>5}: {Counted.count:>7} comparisons, n lg n = {n * math.log2(n):>9.0f}, lg(n!) = {lg_fact:>9.0f}")n = 100: 533 comparisons, n lg n = 664, lg(n!) = 525
n = 1000: 8664 comparisons, n lg n = 9966, lg(n!) = 8529
n = 10000: 120205 comparisons, n lg n = 132877, lg(n!) = 118458
The last column is , the number of yes/no answers needed to tell all orderings apart. The lesson Decision Trees and the Comparison Lower Bound proves that no comparison sort can beat it in the worst case, and the counts here sit only one or two percent above it. Python's sort (Timsort, a merge sort variant) is very close to optimal on random data.
What the course covers
| Section | Algorithms | Main results |
|---|---|---|
| Heaps and heapsort | sift-down, build-heap, heapsort, priority queues | building a heap is ; heapsort is in place |
| Quicksort | Lomuto, Hoare and three-way partitioning, randomized quicksort | worst case ; expected comparisons |
| Lower bounds and linear-time sorting | decision trees, counting, radix and bucket sort | for comparison sorts; and without comparisons |
| Order statistics | min and max, tournaments, quickselect, median of medians | comparisons for both extremes; selection in expected and worst case |
The sorts you will meet, side by side:
| Algorithm | Worst case | Average or expected | In place | Stable |
|---|---|---|---|---|
| insertion sort | yes | yes | ||
| merge sort | no ( extra) | yes | ||
| heapsort | yes | no | ||
| quicksort (randomized) | yes ( stack if done carefully) | no | ||
| counting sort | no | yes | ||
| radix sort | no | yes | ||
| bucket sort | for uniform input | no | yes |
Here is the range of the keys and the number of digits. Insertion sort and merge sort were covered in the foundations course (Counting Steps Exactly, Merge Sort) and are used here as reference points.
The selection problem
The -th order statistic of a set of distinct keys is the -th smallest one. The minimum is the 1st order statistic, the maximum the -th. A median is the middle one: for odd it is unique, at ; for even there are two, the lower median at and the upper median at . Unless stated otherwise, "the median" means the lower median, .
The selection problem: given the keys and , return the -th order statistic. Sorting solves it in time. The last section of the course solves it in , first on average with a randomized algorithm and then in the worst case.
def order_statistic(a, i):
"""The i-th smallest (1-based) by sorting: O(n lg n). The course does better."""
return sorted(a)[i - 1]
a = [31, 7, 19, 4, 26, 12, 40, 15]
n = len(a)
print("sorted: ", sorted(a))
print("minimum: ", order_statistic(a, 1))
print("maximum: ", order_statistic(a, n))
print("lower median:", order_statistic(a, n // 2))
print("upper median:", order_statistic(a, n // 2 + 1))
print("3rd smallest:", order_statistic(a, 3))sorted: [4, 7, 12, 15, 19, 26, 31, 40]
minimum: 4
maximum: 40
lower median: 15
upper median: 19
3rd smallest: 12
Conventions
- Arrays are 0-based and slices are half-open, as in Python: is positions to . Pseudocode is in the same style as the foundations course (How to read pseudocode).
- is and is the natural logarithm.
- Every algorithm comes with a Python version that counts its operations, and the core algorithms also with a C++ version, so you can see what the code looks like in a language with fixed-size arrays and no garbage collector. Random choices use a fixed seed, so you get the output shown.
- Where a topic has a first explanation in the Data Structures and Algorithms course, the lesson links to it rather than repeating it.
The course has practice problems in the practice area: heaps, counting and radix sort, selection and inversions. Each lesson links to the ones it prepares you for.
Test yourself
A sort is stable when...
- it always runs in time
- records with equal keys keep their relative input order
- it uses extra memory
- its running time does not depend on the input order
For distinct keys, which order statistic is the lower median?
- the 3rd smallest
- the 4th smallest
- the 5th smallest
- the average of the 4th and 5th
Why can wrapping keys in a class with a counting __lt__ measure the comparisons of Python's sorted?
- Because
sortedcompares keys only with<, so every comparison goes through__lt__ - Because
sortedcalls__eq__once per element - Because Python times each comparison
- It cannot:
sortedcompares in C, bypassing__lt__