Mini Project: A Sorting Benchmark That Counts Operations
Every lesson of this course made a claim about how many comparisons an algorithm makes: heapsort about , randomized quicksort , insertion sort as many as there are inversions, three-way quicksort a single pass on equal keys. In this project you build a small benchmark that tests all of those claims at once. It runs five sorting algorithms on six input shapes, counts comparisons and moves (writes of elements into the array), checks every result, and compares the counts with the theory.
As in the foundations mini project, the benchmark counts operations instead of measuring seconds: counts are exact, repeatable and the same on every machine. Random choices use fixed seeds, so you get exactly the output shown. Each step is a complete program; later steps repeat the pieces they need, so you can run any of them on its own.
Step 1: A meter for comparisons and moves
Every algorithm receives a Meter and must compare keys only through m.less(x, y), and count each element written into the array. A swap of two different positions counts as two moves; a shift in insertion sort as one.
class Meter:
"""counts key comparisons and element moves (writes into the array)"""
def __init__(self):
self.comparisons = 0
self.moves = 0
def less(self, x, y):
self.comparisons += 1
return x < y
def swap(self, a, i, j):
if i != j:
a[i], a[j] = a[j], a[i]
self.moves += 2
def insertion_sort(a, m):
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and m.less(key, a[j]):
a[j + 1] = a[j]; m.moves += 1
j -= 1
if j + 1 != i:
a[j + 1] = key; m.moves += 1
def heapsort(a, m):
n = len(a)
def sift(i, size):
while True:
l, r, big = 2 * i + 1, 2 * i + 2, i
if l < size and m.less(a[big], a[l]): big = l
if r < size and m.less(a[big], a[r]): big = r
if big == i: return
m.swap(a, i, big); i = big
for i in range(n // 2 - 1, -1, -1):
sift(i, n)
for end in range(n - 1, 0, -1):
m.swap(a, 0, end); sift(0, end)
data = [5, 2, 9, 1, 7, 3, 8, 6, 4]
for sort in [insertion_sort, heapsort]:
a, m = list(data), Meter()
sort(a, m)
print(f"{sort.__name__:>14}: {a} {m.comparisons} comparisons, {m.moves} moves")insertion_sort: [1, 2, 3, 4, 5, 6, 7, 8, 9] 23 comparisons, 24 moves
heapsort: [1, 2, 3, 4, 5, 6, 7, 8, 9] 30 comparisons, 42 moves
Heapsort makes more comparisons than insertion sort here: on 9 elements, insertion sort's has not yet overtaken heapsort's large constant. The next steps show where the crossover lies.
Step 2: Five algorithms, checked
The full set, each instrumented in the same way: insertion sort, merge sort (top-down, merging from a copy of the left half), heapsort, randomized quicksort with Lomuto partitioning, and randomized three-way quicksort. Every algorithm gets an rng argument so the calls look alike, even if it ignores it. The program checks them on 300 random lists with many duplicates, then tests stability by sorting records by a key and checking that equal keys stay in input order.
import random
class Meter:
"""counts key comparisons and element moves (writes into the array)"""
def __init__(self):
self.comparisons = 0
self.moves = 0
def less(self, x, y):
self.comparisons += 1
return x < y
def swap(self, a, i, j):
if i != j:
a[i], a[j] = a[j], a[i]
self.moves += 2
def insertion_sort(a, m, lo=0, hi=None):
hi = len(a) - 1 if hi is None else hi
for i in range(lo + 1, hi + 1):
key, j = a[i], i - 1
while j >= lo and m.less(key, a[j]):
a[j + 1] = a[j]; m.moves += 1
j -= 1
if j + 1 != i:
a[j + 1] = key; m.moves += 1
def merge_sort(a, m):
def sort(lo, hi): # sorts a[lo:hi]
if hi - lo <= 1:
return
mid = (lo + hi) // 2
sort(lo, mid); sort(mid, hi)
left = a[lo:mid]
i, j, k = 0, mid, lo
while i < len(left) and j < hi:
if m.less(a[j], left[i]):
a[k] = a[j]; j += 1
else:
a[k] = left[i]; i += 1
m.moves += 1; k += 1
while i < len(left):
a[k] = left[i]; i += 1; k += 1; m.moves += 1
sort(0, len(a))
def heapsort(a, m):
n = len(a)
def sift(i, size):
while True:
l, r, big = 2 * i + 1, 2 * i + 2, i
if l < size and m.less(a[big], a[l]): big = l
if r < size and m.less(a[big], a[r]): big = r
if big == i: return
m.swap(a, i, big); i = big
for i in range(n // 2 - 1, -1, -1):
sift(i, n)
for end in range(n - 1, 0, -1):
m.swap(a, 0, end); sift(0, end)
def quicksort(a, m, rng):
stack = [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi: continue
m.swap(a, rng.randint(lo, hi), hi)
pivot, i = a[hi], lo
for j in range(lo, hi):
if m.less(a[j], pivot):
m.swap(a, i, j); i += 1
m.swap(a, i, hi)
stack += [(lo, i - 1), (i + 1, hi)]
def quicksort3(a, m, rng):
stack = [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi: continue
m.swap(a, rng.randint(lo, hi), lo)
pivot, lt, i, gt = a[lo], lo, lo, hi
while i <= gt:
if m.less(a[i], pivot):
m.swap(a, lt, i); lt += 1; i += 1
elif m.less(pivot, a[i]):
m.swap(a, i, gt); gt -= 1
else:
i += 1
stack += [(lo, lt - 1), (gt + 1, hi)]
ALGORITHMS = {
"insertion": lambda a, m, rng: insertion_sort(a, m),
"merge": lambda a, m, rng: merge_sort(a, m),
"heap": lambda a, m, rng: heapsort(a, m),
"quick": quicksort,
"quick 3-way": quicksort3,
}
rng = random.Random(5)
for trial in range(300):
data = [rng.randint(0, 20) for _ in range(rng.randint(0, 40))]
for name, sort in ALGORITHMS.items():
a, m = list(data), Meter()
sort(a, m, random.Random(trial))
assert a == sorted(data), name
print("all five algorithms sorted 300 random lists correctly")
# stability: sort (key, original position) pairs by key only
class Key:
def __init__(self, k, pos): self.k, self.pos = k, pos
def __lt__(self, other): return self.k < other.k
data = [Key(rng.randint(0, 3), i) for i in range(40)]
for name, sort in ALGORITHMS.items():
a = list(data)
sort(a, Meter(), random.Random(1))
stable = all(x.k < y.k or (x.k == y.k and x.pos < y.pos) for x, y in zip(a, a[1:]))
print(f"{name:>11}: stable on this input: {stable}")all five algorithms sorted 300 random lists correctly
insertion: stable on this input: True
merge: stable on this input: True
heap: stable on this input: False
quick: stable on this input: False
quick 3-way: stable on this input: False
Insertion and merge sort are stable, as proved in Loop Invariants; heapsort and both quicksorts are not, as Heapsort showed. One input is not a proof of stability, but a single counterexample is a proof of instability.
Step 3: The benchmark table
Six input shapes of keys: random, sorted, reversed, nearly sorted (1 percent of the positions swapped at random), few distinct (only 5 different values) and organ pipe (rising, then falling). The table gives the comparisons, then the moves, for every pair.
import random
class Meter:
"""counts key comparisons and element moves (writes into the array)"""
def __init__(self):
self.comparisons = 0
self.moves = 0
def less(self, x, y):
self.comparisons += 1
return x < y
def swap(self, a, i, j):
if i != j:
a[i], a[j] = a[j], a[i]
self.moves += 2
def insertion_sort(a, m, lo=0, hi=None):
hi = len(a) - 1 if hi is None else hi
for i in range(lo + 1, hi + 1):
key, j = a[i], i - 1
while j >= lo and m.less(key, a[j]):
a[j + 1] = a[j]; m.moves += 1
j -= 1
if j + 1 != i:
a[j + 1] = key; m.moves += 1
def merge_sort(a, m):
def sort(lo, hi): # sorts a[lo:hi]
if hi - lo <= 1:
return
mid = (lo + hi) // 2
sort(lo, mid); sort(mid, hi)
left = a[lo:mid]
i, j, k = 0, mid, lo
while i < len(left) and j < hi:
if m.less(a[j], left[i]):
a[k] = a[j]; j += 1
else:
a[k] = left[i]; i += 1
m.moves += 1; k += 1
while i < len(left):
a[k] = left[i]; i += 1; k += 1; m.moves += 1
sort(0, len(a))
def heapsort(a, m):
n = len(a)
def sift(i, size):
while True:
l, r, big = 2 * i + 1, 2 * i + 2, i
if l < size and m.less(a[big], a[l]): big = l
if r < size and m.less(a[big], a[r]): big = r
if big == i: return
m.swap(a, i, big); i = big
for i in range(n // 2 - 1, -1, -1):
sift(i, n)
for end in range(n - 1, 0, -1):
m.swap(a, 0, end); sift(0, end)
def quicksort(a, m, rng):
stack = [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi: continue
m.swap(a, rng.randint(lo, hi), hi)
pivot, i = a[hi], lo
for j in range(lo, hi):
if m.less(a[j], pivot):
m.swap(a, i, j); i += 1
m.swap(a, i, hi)
stack += [(lo, i - 1), (i + 1, hi)]
def quicksort3(a, m, rng):
stack = [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi: continue
m.swap(a, rng.randint(lo, hi), lo)
pivot, lt, i, gt = a[lo], lo, lo, hi
while i <= gt:
if m.less(a[i], pivot):
m.swap(a, lt, i); lt += 1; i += 1
elif m.less(pivot, a[i]):
m.swap(a, i, gt); gt -= 1
else:
i += 1
stack += [(lo, lt - 1), (gt + 1, hi)]
def make_inputs(n, seed):
rng = random.Random(seed)
nearly = list(range(n))
for _ in range(n // 100): # 1 percent random swaps
i, j = rng.randrange(n), rng.randrange(n)
nearly[i], nearly[j] = nearly[j], nearly[i]
return {
"random": rng.sample(range(n), n),
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1)),
"nearly sorted": nearly,
"few distinct": [rng.randrange(5) for _ in range(n)],
"organ pipe": list(range(0, n, 2)) + list(range(n - 1, 0, -2)),
}
ALGORITHMS = {
"insertion": lambda a, m, rng: insertion_sort(a, m),
"merge": lambda a, m, rng: merge_sort(a, m),
"heap": lambda a, m, rng: heapsort(a, m),
"quick": quicksort,
"quick 3-way": quicksort3,
}
n = 500
inputs = make_inputs(n, seed=1)
for measure in ["comparisons", "moves"]:
print(f"{measure} for n = {n}")
print(f"{'input':>13}" + "".join(f"{name:>12}" for name in ALGORITHMS))
for shape, data in inputs.items():
row = []
for name, sort in ALGORITHMS.items():
a, m = list(data), Meter()
sort(a, m, random.Random(2))
assert a == sorted(data)
row.append(getattr(m, measure))
print(f"{shape:>13}" + "".join(f"{v:>12}" for v in row))
print()comparisons for n = 500
input insertion merge heap quick quick 3-way
random 62203 3864 7429 4820 7532
sorted 499 2216 7756 5197 8262
reversed 124750 2272 7010 5327 9191
nearly sorted 2112 2783 7739 5113 8075
few distinct 54092 3640 6396 26267 2072
organ pipe 62749 2493 7624 5404 9478
moves for n = 500
input insertion merge heap quick quick 3-way
random 62201 4161 8132 5364 9100
sorted 0 2216 8708 984 10576
reversed 125249 4488 7352 3780 11116
nearly sorted 1995 2805 8670 1946 10974
few distinct 53988 3832 6542 3484 1960
organ pipe 62499 3476 8248 4600 11712
Things to read off the table, each one a result from the course:
- Insertion sort is the best algorithm in the table on sorted and nearly sorted input ( comparisons when sorted) and the worst everywhere else; on reversed input it makes exactly comparisons. Its comparisons track the number of inversions (Counting Steps Exactly).
- Heapsort hardly notices the input shape: between about 6,400 and 7,800 comparisons on every row, close to minus a linear term.
- Randomized quicksort costs about the same on every input without duplicates, as the analysis promises, but it is quadratic on few distinct values, because Lomuto's partition sends all keys equal to the pivot to one side (Lomuto Partitioning).
- Three-way quicksort fixes exactly that row (about comparisons with 5 distinct keys) and pays for it with two comparisons per element on distinct keys (Three-Way Partitioning).
- Merge sort makes the fewest comparisons of the sorts on every row except few distinct, where three-way quicksort wins, and it is cheapest on sorted and reversed input, where every merge stops comparing as soon as one half runs out.
Step 4: Growth and constants
The table is a snapshot at one size. To compare with the theory, measure on random input at doubling sizes and divide by . For reference the program also prints the lower bound from Decision Trees and the exact expected count of randomized quicksort from Randomized Quicksort, both divided by .
import math, random
class Meter:
"""counts key comparisons and element moves (writes into the array)"""
def __init__(self):
self.comparisons = 0
self.moves = 0
def less(self, x, y):
self.comparisons += 1
return x < y
def swap(self, a, i, j):
if i != j:
a[i], a[j] = a[j], a[i]
self.moves += 2
def insertion_sort(a, m, lo=0, hi=None):
hi = len(a) - 1 if hi is None else hi
for i in range(lo + 1, hi + 1):
key, j = a[i], i - 1
while j >= lo and m.less(key, a[j]):
a[j + 1] = a[j]; m.moves += 1
j -= 1
if j + 1 != i:
a[j + 1] = key; m.moves += 1
def merge_sort(a, m):
def sort(lo, hi): # sorts a[lo:hi]
if hi - lo <= 1:
return
mid = (lo + hi) // 2
sort(lo, mid); sort(mid, hi)
left = a[lo:mid]
i, j, k = 0, mid, lo
while i < len(left) and j < hi:
if m.less(a[j], left[i]):
a[k] = a[j]; j += 1
else:
a[k] = left[i]; i += 1
m.moves += 1; k += 1
while i < len(left):
a[k] = left[i]; i += 1; k += 1; m.moves += 1
sort(0, len(a))
def heapsort(a, m):
n = len(a)
def sift(i, size):
while True:
l, r, big = 2 * i + 1, 2 * i + 2, i
if l < size and m.less(a[big], a[l]): big = l
if r < size and m.less(a[big], a[r]): big = r
if big == i: return
m.swap(a, i, big); i = big
for i in range(n // 2 - 1, -1, -1):
sift(i, n)
for end in range(n - 1, 0, -1):
m.swap(a, 0, end); sift(0, end)
def quicksort(a, m, rng):
stack = [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi: continue
m.swap(a, rng.randint(lo, hi), hi)
pivot, i = a[hi], lo
for j in range(lo, hi):
if m.less(a[j], pivot):
m.swap(a, i, j); i += 1
m.swap(a, i, hi)
stack += [(lo, i - 1), (i + 1, hi)]
def quicksort3(a, m, rng):
stack = [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi: continue
m.swap(a, rng.randint(lo, hi), lo)
pivot, lt, i, gt = a[lo], lo, lo, hi
while i <= gt:
if m.less(a[i], pivot):
m.swap(a, lt, i); lt += 1; i += 1
elif m.less(pivot, a[i]):
m.swap(a, i, gt); gt -= 1
else:
i += 1
stack += [(lo, lt - 1), (gt + 1, hi)]
ALGORITHMS = {
"insertion": lambda a, m, rng: insertion_sort(a, m),
"merge": lambda a, m, rng: merge_sort(a, m),
"heap": lambda a, m, rng: heapsort(a, m),
"quick": quicksort,
"quick 3-way": quicksort3,
}
fast = {k: v for k, v in ALGORITHMS.items() if k != "insertion"}
sizes = [500, 1000, 2000]
print(f"{'':>11}" + "".join(f"{'n = ' + str(n):>12}" for n in sizes) + " (comparisons / n lg n, random input, mean of 3 runs)")
for name, sort in fast.items():
row = []
for n in sizes:
total = 0
for run in range(3):
data = random.Random(100 * n + run).sample(range(n), n)
m = Meter()
sort(data, m, random.Random(run))
total += m.comparisons
row.append(total / 3 / (n * math.log2(n)))
print(f"{name:>11}" + "".join(f"{r:>12.3f}" for r in row))
for n in sizes:
H = sum(1 / k for k in range(1, n + 1))
print(f"n = {n}: lg(n!) / n lg n = {math.lgamma(n + 1) / math.log(2) / (n * math.log2(n)):.3f}, "
f"quicksort theory (2(n+1)H_n - 4n) / n lg n = {(2 * (n + 1) * H - 4 * n) / (n * math.log2(n)):.3f}") n = 500 n = 1000 n = 2000 (comparisons / n lg n, random input, mean of 3 runs)
merge 0.861 0.874 0.886
heap 1.657 1.692 1.721
quick 1.071 1.088 1.098
quick 3-way 1.681 1.726 1.717
n = 500: lg(n!) / n lg n = 0.840, quicksort theory (2(n+1)H_n - 4n) / n lg n = 1.072
n = 1000: lg(n!) / n lg n = 0.856, quicksort theory (2(n+1)H_n - 4n) / n lg n = 1.102
n = 2000: lg(n!) / n lg n = 0.869, quicksort theory (2(n+1)H_n - 4n) / n lg n = 1.128
- Quicksort's measured ratios sit right next to the theory row, within a few percent.
- Merge sort stays just above the lower bound, as the decision-tree lesson predicted.
- Heapsort is about twice the lower bound, and three-way quicksort's extra comparison per element makes it similar to heapsort on distinct keys.
- The ratios still creep upwards (three-way quicksort's wobble is sampling noise from only three runs). That is the lower-order term fading as grows (), not a sign of super- growth: the limits are 1 for merge sort, 2 for heapsort and for quicksort.
Step 5: The core in C++, against the standard library
The same measurement in C++, with . The trick is a key type, Item, whose < operator and copy operations increment counters; any algorithm that sorts Items, including the standard library's, is then measured without changing its code. The table compares GCC's std::sort (introsort), std::stable_sort (merge sort), heapsort through std::make_heap and std::sort_heap, and the randomized Lomuto quicksort of this course.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <functional>
#include <random>
#include <string>
#include <utility>
#include <vector>
// A key that counts every comparison and every move (copy or move assignment/construction).
struct Item {
int key = 0;
static inline long long comparisons = 0, moves = 0;
Item() = default;
explicit Item(int k) : key(k) {}
Item(const Item& o) : key(o.key) { ++moves; }
Item& operator=(const Item& o) { key = o.key; ++moves; return *this; }
friend bool operator<(const Item& a, const Item& b) { ++comparisons; return a.key < b.key; }
};
void quicksort(std::vector<Item>& a, int lo, int hi, std::mt19937& rng) { // randomized, Lomuto
while (lo < hi) {
int r = lo + static_cast<int>(rng() % static_cast<unsigned>(hi - lo + 1));
std::swap(a[r], a[hi]);
int i = lo;
for (int j = lo; j < hi; ++j)
if (a[j] < a[hi]) { if (i != j) std::swap(a[i], a[j]); ++i; }
std::swap(a[i], a[hi]);
if (i - lo < hi - i) { quicksort(a, lo, i - 1, rng); lo = i + 1; } // smaller side first
else { quicksort(a, i + 1, hi, rng); hi = i - 1; }
}
}
int main() {
const int n = 10000;
std::mt19937 gen(1);
std::vector<std::pair<std::string, std::vector<int>>> inputs;
std::vector<int> v(n);
for (int i = 0; i < n; ++i) v[i] = i;
inputs.push_back({"sorted", v});
std::vector<int> rev(v.rbegin(), v.rend());
inputs.push_back({"reversed", rev});
for (int i = n - 1; i > 0; --i) std::swap(v[i], v[gen() % (i + 1)]);
inputs.push_back({"random", v});
std::vector<int> few(n);
for (int& x : few) x = static_cast<int>(gen() % 5);
inputs.push_back({"few distinct", few});
std::vector<std::pair<std::string, std::function<void(std::vector<Item>&)>>> algorithms = {
{"std::sort", [](std::vector<Item>& a) { std::sort(a.begin(), a.end()); }},
{"std::stable_sort", [](std::vector<Item>& a) { std::stable_sort(a.begin(), a.end()); }},
{"heap (std)", [](std::vector<Item>& a) { std::make_heap(a.begin(), a.end()); std::sort_heap(a.begin(), a.end()); }},
{"quicksort", [](std::vector<Item>& a) { std::mt19937 rng(7); quicksort(a, 0, static_cast<int>(a.size()) - 1, rng); }},
};
std::printf("n = %d, n lg n = %.0f; each cell: comparisons / moves\n", n, n * std::log2(n));
std::printf("%-13s", "input");
for (auto& [name, f] : algorithms) std::printf("%22s", name.c_str());
std::printf("\n");
for (auto& [shape, data] : inputs) {
std::printf("%-13s", shape.c_str());
for (auto& [name, sort] : algorithms) {
std::vector<Item> a;
for (int x : data) a.emplace_back(x);
Item::comparisons = Item::moves = 0;
sort(a);
long long c = Item::comparisons, m = Item::moves;
bool ok = std::is_sorted(a.begin(), a.end(), [](const Item& x, const Item& y) { return x.key < y.key; });
std::printf("%15lld /%6lld%s", c, m, ok ? "" : "!");
}
std::printf("\n");
}
}n = 10000, n lg n = 132877; each cell: comparisons / moves
input std::sort std::stable_sort heap (std) quicksort
sorted 166691 / 34872 73534 /132141 137505 /192618 154293 / 39954
reversed 122058 / 47040 59020 /167131 141016 /201054 169092 /247947
random 159559 /119490 127809 /151986 136706 /192792 160853 /257436
few distinct 113963 /148740 120296 /148313 133315 /189072 10015742 /102414
std::sortnever comes near the quadratic case: introsort's median-of-three pivots and its depth limit protect it (Quicksort in Practice), and its partition handles equal keys like Hoare's scheme, so few distinct values are cheap.std::stable_sortmakes the fewest comparisons on most rows, like merge sort in step 3, but moves far more elements thanstd::sort, because merging copies through a buffer.- The textbook quicksort is fine on distinct keys and quadratic on few distinct keys: over 10 million comparisons, against about 114,000 for
std::sort. Of all the lessons in this course, that one row is the most important in practice.
Ideas to extend the benchmark
- Add median-of-three pivot selection and an insertion-sort cutoff to the quicksort of step 2, and measure how comparisons and moves change on each row.
- Add Hoare partitioning and check that the few-distinct row becomes without three-way partitioning.
- Add counting sort for the few-distinct input and radix sort for random integers. They make no key comparisons at all, so count array reads and writes instead, and compare the totals.
- Record the maximum stack depth of each quicksort variant, with and without the smaller-side-first rule.
- Compare the number of inversions of each input with insertion sort's comparison count; they should differ by at most .
- For selection, add quickselect and median of medians and measure comparisons for the median on the same six shapes.
Test yourself
In the step 3 table, why is randomized quicksort slow on the few-distinct input but fast on the others?
- Because the random pivot is badly chosen
- Because Lomuto partitioning sends every key equal to the pivot to one side, so blocks of equal keys are peeled off one element at a time
- Because the input is already sorted
- Because the meter counts too many comparisons
Why do the measured ratios comparisons / still increase slowly with for merge sort and heapsort?
- Because the algorithms are slower than
- Because the counts have a negative linear term, , whose relative size shrinks as grows
- Because of the random seeds
- Because Python is slow
How does the C++ benchmark measure std::sort without changing the library's code?
- By timing it
- By sorting a key type whose comparison and copy operations increment counters
- By reading the compiler's output
- By counting function calls with a debugger