Sub topic 14
Testing Whether a Sort Is Stable
This chapter assumes you know the definition of a stable sort, can write a key function, and can read Python. Its question is practical: given a sort function you didn't write, how do you find out whether it keeps equal elements in their input order? The documentation may be silent, out of date, or describe a different version than the one you run. A short test settles it.
The idea: tag every element with its position
A stable sort keeps equal keys in input order. To check that, the test has to know each element's input order. So you pair each key with its original index, sort on the key alone, and then inspect the output. Wherever two neighbours share a key, their indices must increase.
A reusable checker
The checker below also confirms that the output is sorted and holds exactly the input elements. Without those checks, a function that returned its input unchanged could look stable.
import random
def check_sort(sort_fn, n=1000, distinct_keys=10, trials=20, seed=0):
rng = random.Random(seed)
for _ in range(trials):
data = [(rng.randrange(distinct_keys), i) for i in range(n)]
result = sort_fn(list(data), key=lambda pair: pair[0])
# Same elements: sorting the output by index must rebuild the input.
if sorted(result, key=lambda pair: pair[1]) != data:
return "lost or duplicated elements"
for a, b in zip(result, result[1:]):
if a[0] > b[0]:
return "not sorted"
if a[0] == b[0] and a[1] > b[1]:
return "unstable"
return "ok"
def selection_sort(items, key):
items = list(items)
for i in range(len(items)):
m = i
for j in range(i + 1, len(items)):
if key(items[j]) < key(items[m]):
m = j
# This long-distance swap can jump an element past an equal one.
items[i], items[m] = items[m], items[i]
return items
print(check_sort(sorted)) # ok
print(check_sort(selection_sort)) # unstablePython's sorted passes every trial. Selection sort fails on the first trial. Its swap carries an element across a stretch of the list, and with 1,000 elements and only 10 distinct keys, that swap is all but certain to pass over an equal key.
Choices that make the test effective
| Choice | Why it matters |
|---|---|
| Few distinct keys | Many ties give an unstable sort many chances to misorder them. With all-distinct keys, every sort looks stable. |
| Sort on the key only | If the comparator also compares the index, every correct sort produces index order among ties, and the test proves nothing. |
| Several trials, fixed seed | Instability may show up only for some inputs. A fixed seed makes failures reproducible. |
| Check sortedness and contents | A broken sort can pass a stability check by accident. |
| Large inputs too | Hybrid sorts switch algorithm by size. Introsort and pdqsort, for example, use insertion sort on small ranges. A sort can be stable below the cutoff and unstable above it. |
Adapting it to other languages
The pattern carries over to other languages directly. In C++, build a std::vector<std::pair<int, std::size_t>> and sort it with a comparator that compares only .first. In Go, compare only the key field inside the less function you pass to sort.Slice or sort.SliceStable. Running the test against sort.Slice on a large input with many ties will usually show reordered equal elements. That result is why Go code that depends on tie order must call sort.SliceStable.
The same harness can test the index-tiebreaker technique from an earlier chapter. Wrap an unstable sort with the tiebreaker, pass the wrapper to check_sort, and confirm that it reports ok.
Exercise
A colleague tests stability by calling sort_fn(data) on the (key, index) pairs with no key function, and every sort they try passes. What is wrong with the test?
Show answer
Without a key function, the sort compares whole tuples, so ties on the key are broken by the index. Any correct sort then puts equal keys in index order, whether it is stable or not. The test must compare the key alone.
Exercise
Why would checksort(selectionsort, distinctkeys=1000_000) probably report "ok"?
Show answer
With a million possible keys and only 1,000 elements, most keys are unique and there are almost no ties. Instability can only show up among equal keys, so the test has nothing to detect.