Sub topic 14
Testing Whether a Sort Is Stable
This chapter assumes you already know what a stable sort is, how key functions and comparators work, and why library sorts often switch to insertion sort for small inputs. The examples use Python, plus one C++ program. You should be comfortable writing small test functions and running them with pytest or a plain script.
Testing for stability is one-sided. A single failing case proves a sort is unstable. Any number of passing cases only shows that the sort behaved stably on those inputs. Some unstable sorts look stable on most inputs, so a test is only as good as the inputs it uses. This chapter covers how to build a test that actually catches instability and avoids the common ways such tests pass by accident.
The Core Technique: Tag Every Element with Its Position
Stability is about the input order of elements whose keys are equal. To see that order after sorting, you record it before sorting. Pair each key with its original index, sort on the key alone, then check that equal keys come out with increasing indices.
import random
def is_stable(sort_fn, n=1000, distinct_keys=10):
data = [(random.randrange(distinct_keys), i) for i in range(n)]
result = sort_fn(data, key=lambda pair: pair[0])
return all(
a[1] < b[1]
for a, b in zip(result, result[1:])
if a[0] == b[0]
)
print(is_stable(sorted)) # TrueThe key function must look only at pair[0]. If you sort the tuples directly, Python compares the index as a tiebreaker, so every element becomes unique and any sort would pass.
Checking adjacent pairs is enough. In sorted output, all elements with the same key sit in one contiguous block. If each neighbouring pair in that block has increasing indices, the whole block is increasing by transitivity.
Check Sortedness and Permutation Too
The is_stable function above has a blind spot. A "sort" that returns its input unchanged passes, because the indices are already increasing everywhere. So does a sort that drops elements. A stability check only means something if the output is also a correctly sorted rearrangement of the input. A complete checker tests all three properties:
from collections import Counter
def check_sort(sort_fn, data, key):
result = sort_fn(list(data), key=key)
if Counter(result) != Counter(data):
return "not a permutation"
if any(key(b) < key(a) for a, b in zip(result, result[1:])):
return "not sorted"
for a, b in zip(result, result[1:]):
if key(a) == key(b) and a[1] > b[1]:
return "not stable"
return "ok"The checker passes a copy (list(data)) so that in-place sorts cannot change the reference data. It expects sort_fn to return the sorted list. sorted does this, but list.sort returns None, so wrap it first:
def list_sort(items, key):
items.sort(key=key)
return items| Check | Bug it catches | What happens if you skip it |
|---|---|---|
| Permutation | Lost, duplicated or corrupted elements | A sort that drops ties can pass |
| Sorted by key | Wrong comparisons, off-by-one loops | The identity function passes |
| Increasing index among equal keys | Instability | You are not testing stability |
Catching Real Unstable Sorts
A test should prove its worth by failing on code you know is wrong. Here are two such sorts. Selection sort is unstable because its long-distance swap can jump an element over an equal one. The insertion sort below has the >= mutation that the earlier chapter warned about.
def selection_sort(items, key):
n = len(items)
for i in range(n):
m = i
for j in range(i + 1, n):
if key(items[j]) < key(items[m]):
m = j
items[i], items[m] = items[m], items[i]
return items
def insertion_sort_broken(items, key):
for i in range(1, len(items)):
current = items[i]
j = i - 1
while j >= 0 and key(items[j]) >= key(current): # should be '>'
items[j + 1] = items[j]
j -= 1
items[j + 1] = current
return items
def run_trials(sort_fn, trials=200, max_n=300, max_keys=8, seed=0):
rng = random.Random(seed)
for _ in range(trials):
n = rng.randrange(0, max_n)
k = rng.randrange(1, max_keys + 1)
data = [(rng.randrange(k), i) for i in range(n)]
verdict = check_sort(sort_fn, data, key=lambda p: p[0])
if verdict != "ok":
return verdict, len(data)
return "ok", None
for fn in (sorted, list_sort, selection_sort, insertion_sort_broken):
print(fn.__name__, run_trials(fn))Running this prints ok for sorted and list_sort, and not stable for the other two. A fixed seed makes any failure reproducible. When you hunt for rare failures, change the seed or loop over many seeds.
Inputs that expose instability
The way you generate input decides what the test can find:
- Few distinct keys. With 1000 elements and 1000 possible keys, most keys are unique and there are almost no ties to reorder. Use somewhere between 1 and about 10 distinct keys.
- All keys equal. This is the strongest single case. A stable sort must return the input order unchanged, so the expected output is known exactly.
- Sizes above the small-array cutoff. Library sorts hand small ranges to insertion sort, which is stable. libstdc++'s
std::sortdoes this for ranges of 16 elements or fewer, and other hybrids use cutoffs of a few dozen elements. A test that only uses 10 elements can pass against an unstable sort. - Structured inputs. Include already sorted, reversed, and sawtooth inputs alongside random ones. Hybrids like pdqsort and Timsort take different code paths for these patterns.
Seeing the Small-Input Trap in C++
This program counts stability violations for std::sort and std::stable_sort at two sizes.
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <random>
#include <utility>
#include <vector>
template <class Sort>
std::size_t count_violations(Sort sort_fn, std::size_t n, int distinct, unsigned seed) {
std::mt19937 rng(seed);
std::uniform_int_distribution<int> dist(0, distinct - 1);
std::vector<std::pair<int, std::size_t>> v;
for (std::size_t i = 0; i < n; ++i) v.emplace_back(dist(rng), i);
sort_fn(v);
std::size_t bad = 0;
for (std::size_t i = 1; i < v.size(); ++i)
if (v[i - 1].first == v[i].first && v[i - 1].second > v[i].second) ++bad;
return bad;
}
int main() {
auto by_key = [](const auto& a, const auto& b) { return a.first < b.first; };
auto unstable = [&](auto& v) { std::sort(v.begin(), v.end(), by_key); };
auto stable = [&](auto& v) { std::stable_sort(v.begin(), v.end(), by_key); };
for (std::size_t n : {10, 1000}) {
std::cout << "n=" << n
<< " sort: " << count_violations(unstable, n, 5, 42)
<< " stable_sort: " << count_violations(stable, n, 5, 42) << '\n';
}
}With libstdc++, std::sort typically reports 0 violations at n=10 and many at n=1000. std::stable_sort reports 0 at both sizes. The exact counts depend on the library and its version. The pattern holds, though: below the cutoff, the unstable sort runs insertion sort and looks stable.
Property-Based Testing
A property-based testing library generates inputs for you. When a test fails, it shrinks the failing input to a small example. In Python, Hypothesis does this (pip install hypothesis pytest). Put this test in the same file as check_sort:
from hypothesis import given, strategies as st
@given(st.lists(st.integers(min_value=0, max_value=5), max_size=500))
def test_sorted_is_stable(keys):
data = [(k, i) for i, k in enumerate(keys)]
assert check_sort(sorted, data, key=lambda p: p[0]) == "ok"The narrow integer range forces many ties. Point the same test at selection_sort and Hypothesis shrinks the failure to about three elements, for example keys [1, 1, 0]. That is much easier to debug than a 300-element list.
Test the Comparator Before the Sort
The stability check compares elements for equality, and "equal" only means something if the comparator is a strict weak ordering. If the comparator breaks that contract, "elements with equal keys" is not well defined. The sort may then produce any order, and the stability result tells you nothing. Java may throw IllegalArgumentException: Comparison method violates its general contract!, and in C++ a broken comparator is undefined behaviour.
A brute-force checker over a small sample of values finds most contract violations:
def check_strict_weak_order(less, values):
def equiv(x, y):
return not less(x, y) and not less(y, x)
for a in values:
if less(a, a):
return f"irreflexivity fails: {a!r}"
for a in values:
for b in values:
if less(a, b) and less(b, a):
return f"asymmetry fails: {a!r}, {b!r}"
for c in values:
if less(a, b) and less(b, c) and not less(a, c):
return f"transitivity fails: {a!r}, {b!r}, {c!r}"
if equiv(a, b) and equiv(b, c) and not equiv(a, c):
return f"equivalence not transitive: {a!r}, {b!r}, {c!r}"
return "ok"
def fuzzy_less(a, b):
return b - a > 0.5 # "close enough counts as equal"
print(check_strict_weak_order(lambda a, b: a < b, [0, 0.4, 0.8, 3])) # ok
print(check_strict_weak_order(fuzzy_less, [0, 0.4, 0.8]))
# equivalence not transitive: 0, 0.4, 0.8The checker runs in cubic time, so keep the sample to a few dozen values. Include edge cases in it: duplicates, negative numbers, empty strings and, for floats, NaN. NaN compares false with everything, so a plain < on floats containing NaN is not a strict weak ordering.
Exercise
A colleague's test generates 50 random integers from 0 to 1,000,000, tags each with its index, sorts with std::sort, and checks that equal keys have increasing indices. The test always passes. Give two reasons it is weak, and say how to fix each.
Show answer
First, keys drawn from a million possible values almost never repeat, so there are no ties to reorder. Use a handful of distinct keys, or make every key equal. Second, 50 elements is only a little above libstdc++'s 16-element insertion sort cutoff, and the test does not vary the size or the input shape. Use sizes in the hundreds or thousands, and add sorted, reversed and random patterns. The test should also check that the output is sorted and is a permutation of the input.
Exercise
Why does check_sort verify that the output is a permutation of the input before it checks stability? Name a broken sort that would pass a stability-only check.
Show answer
The stability check only compares indices inside groups of equal keys that appear in the output. A function that returns its input unchanged passes, because the indices are already increasing. So does one that returns an empty list or drops all but one element of each group. The permutation and sortedness checks rule these out.
Exercise
Write a deterministic test, with no randomness, that any correct stable sort passes and selection_sort from this chapter fails.
Show answer
Use data = [(1, 0), (1, 1), (0, 2)] with key=lambda p: p[0]. A stable sort returns [(0, 2), (1, 0), (1, 1)]. On its first pass, selectionsort swaps position 0 with position 2 and gets [(0, 2), (1, 1), (1, 0)]. So assert checksort(selection_sort, data, key=lambda p: p[0]) == "not stable", and assert that the same check on sorted returns "ok".