TExcelTAD
Home › Sorting & Order Statistics › Sorting and Selection: What This Course Covers

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 nlg⁡nn \lg n 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 a0,a1,…,an−1a_0, a_1, \ldots, a_{n-1} of keys from a totally ordered set.
  • Output: a permutation b0,…,bn−1b_0, \ldots, b_{n-1} of the input with b0≤b1≤⋯≤bn−1b_0 \le b_1 \le \cdots \le b_{n-1}.

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 O(1)O(1) memory besides the array (some authors allow O(lg⁡n)O(\lg n) 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.

python · try it yourself
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.

python · try it yourself
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 lg⁡(n!)\lg(n!), the number of yes/no answers needed to tell all n!n! 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 Θ(n)\Theta(n); heapsort is O(nlg⁡n)O(n \lg n) in place
Quicksort Lomuto, Hoare and three-way partitioning, randomized quicksort worst case Θ(n2)\Theta(n^2); expected 2nln⁡n+O(n)2n \ln n + O(n) comparisons
Lower bounds and linear-time sorting decision trees, counting, radix and bucket sort Ω(nlg⁡n)\Omega(n \lg n) for comparison sorts; Θ(n+k)\Theta(n + k) and Θ(d(n+k))\Theta(d(n + k)) without comparisons
Order statistics min and max, tournaments, quickselect, median of medians 3⌊n/2⌋3\lfloor n/2 \rfloor comparisons for both extremes; selection in O(n)O(n) expected and worst case

The sorts you will meet, side by side:

Algorithm Worst case Average or expected In place Stable
insertion sort Θ(n2)\Theta(n^2) Θ(n2)\Theta(n^2) yes yes
merge sort Θ(nlg⁡n)\Theta(n \lg n) Θ(nlg⁡n)\Theta(n \lg n) no (Θ(n)\Theta(n) extra) yes
heapsort Θ(nlg⁡n)\Theta(n \lg n) Θ(nlg⁡n)\Theta(n \lg n) yes no
quicksort (randomized) Θ(n2)\Theta(n^2) Θ(nlg⁡n)\Theta(n \lg n) yes (O(lg⁡n)O(\lg n) stack if done carefully) no
counting sort Θ(n+k)\Theta(n + k) Θ(n+k)\Theta(n + k) no yes
radix sort Θ(d(n+k))\Theta(d(n + k)) Θ(d(n+k))\Theta(d(n + k)) no yes
bucket sort Θ(n2)\Theta(n^2) Θ(n)\Theta(n) for uniform input no yes

Here kk is the range of the keys and dd 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 ii-th order statistic of a set of nn distinct keys is the ii-th smallest one. The minimum is the 1st order statistic, the maximum the nn-th. A median is the middle one: for odd nn it is unique, at i=(n+1)/2i = (n+1)/2; for even nn there are two, the lower median at i=n/2i = n/2 and the upper median at i=n/2+1i = n/2 + 1. Unless stated otherwise, "the median" means the lower median, i=⌊(n+1)/2⌋i = \lfloor (n+1)/2 \rfloor.

The selection problem: given the nn keys and ii, return the ii-th order statistic. Sorting solves it in O(nlg⁡n)O(n \lg n) time. The last section of the course solves it in O(n)O(n), first on average with a randomized algorithm and then in the worst case.

python · try it yourself
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: a[lo:hi]a[lo:hi] is positions lolo to hi−1hi - 1. Pseudocode is in the same style as the foundations course (How to read pseudocode).
  • lg⁡n\lg n is log⁡2n\log_2 n and ln⁡n\ln n 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...

  1. it always runs in O(nlg⁡n)O(n \lg n) time
  2. records with equal keys keep their relative input order
  3. it uses O(1)O(1) extra memory
  4. its running time does not depend on the input order

For n=8n = 8 distinct keys, which order statistic is the lower median?

  1. the 3rd smallest
  2. the 4th smallest
  3. the 5th smallest
  4. 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?

  1. Because sorted compares keys only with <, so every comparison goes through __lt__
  2. Because sorted calls __eq__ once per element
  3. Because Python times each comparison
  4. It cannot: sorted compares in C, bypassing __lt__