Sub topic 8
Writing Comparators the Library Can Trust
This chapter assumes you can pass a lambda to a sort function and that you know the difference between a key function and a comparator from the chapter on keys and comparators. It also assumes you know what a stable sort promises. Here we look at the other side of that promise. A sort function can only be correct, and only be stable, if the comparator you give it follows certain rules. Break the rules and you can get a wrong order, an exception, or in C++ a crash.
Why the Contract Exists
A sort algorithm never looks at your data directly. It only asks "does a come before b?" and trusts the answer. Every shortcut a fast sort takes depends on that trust. Insertion sort stops scanning once it finds an element that is not greater. Quicksort's partition loop may run without bounds checks because it assumes the pivot will stop it. Timsort skips ahead during galloping because it assumes that if a < b and b < c, then a < c.
Stability depends on the same answers. A stable sort keeps the input order among elements the comparator calls equivalent, meaning neither one comes before the other. If the comparator's idea of "equivalent" is inconsistent, the groups of equal elements are not well defined, and "keep their input order" has no clear meaning.
The Rules: Strict Weak Ordering
Most libraries require a strict weak ordering. Write less(a, b) for "a comes before b". The four rules are:
| Rule | Statement | What breaks it |
|---|---|---|
| Irreflexivity | `less(a, a)` is false | Using `<=` instead of `<` |
| Asymmetry | if `less(a, b)` then not `less(b, a)` | Random or state-dependent answers |
| Transitivity | `less(a, b)` and `less(b, c)` imply `less(a, c)` | Rock-paper-scissors style rules, integer overflow |
| Transitivity of equivalence | if `a ~ b` and `b ~ c` then `a ~ c`, where `x ~ y` means neither is less | Tolerance comparisons on floats, NaN |
The fourth rule is the one people forget. It is what splits the elements into clean groups of equal keys, and a stable sort needs exactly those groups.
Three-way comparators, which return negative, zero or positive as in Java's compare or JavaScript's sort callback, have the same rules written differently. The sign of compare(a, b) must be the opposite of the sign of compare(b, a). It must be transitive. If compare(a, b) == 0, then a and b must compare the same way against every other element.
A comparator must also be deterministic. It has to give the same answer every time for the same pair during the sort. That rules out reading mutable state, calling a random number generator, or changing the elements' keys while the sort is running.
What Happens When You Break the Rules
The consequences differ by language, and some of them are severe.
| Language and function | Behavior on a contract violation |
|---|---|
| C++ `std::sort`, `std::stable_sort` | Undefined behavior. Results can be wrong, and `std::sort` can read past the end of the range and crash. |
| Java `List.sort`, `Arrays.sort` (objects) | May throw `IllegalArgumentException: Comparison method violates its general contract!`, or may return a wrong order. |
| Python `sorted`, `list.sort` | No exception from the contract itself. The result is still a permutation of the input, but the order is unspecified. |
| JavaScript `Array.prototype.sort` | The specification calls the resulting order implementation-defined. |
| Rust `sort`, `sort_unstable` | Memory-safe. The order is unspecified, and since Rust 1.81 the sort may panic if it detects the violation. |
| Go `sort.Slice`, `slices.SortFunc` | Unspecified order. |
The Java exception is a frequent source of confusion because it is intermittent. Timsort only detects the inconsistency during certain merges, so a buggy comparator can pass small tests and then fail in production on a larger list.
Common Comparator Bugs
Using `<=` Where `<` Is Required
In C++, Go's less functions, and any other API that asks for a "less than" predicate, <= violates irreflexivity, because a <= a is true. With many equal elements, libstdc++'s std::sort can walk off the end of the array during its unguarded insertion pass. The fix is always a strict comparison. For several fields, std::tie builds tuples that compare lexicographically and gets this right for you.
#include <algorithm>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
struct Employee {
std::string dept;
int salary;
std::string name;
};
int main() {
std::vector<Employee> staff = {
{"eng", 120, "ana"}, {"ops", 90, "raj"},
{"eng", 150, "li"}, {"eng", 120, "bo"},
};
// Wrong: return a.salary <= b.salary; (not irreflexive: undefined behavior)
// Right: dept ascending, salary descending, name ascending.
// Swapping a.salary and b.salary inside the tuples reverses that one field.
std::sort(staff.begin(), staff.end(), [](const Employee& a, const Employee& b) {
return std::tie(a.dept, b.salary, a.name) < std::tie(b.dept, a.salary, b.name);
});
for (const auto& e : staff)
std::cout << e.dept << ' ' << e.salary << ' ' << e.name << '\n';
// eng 150 li
// eng 120 ana
// eng 120 bo
// ops 90 raj
}Subtraction That Overflows
The idiom (a, b) -> a - b looks like a neat three-way comparator. With 32-bit integers in Java, C, C++ or Go it can overflow and flip the sign, which breaks transitivity.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
Comparator<Integer> bad = (a, b) -> a - b;
Comparator<Integer> good = Integer::compare;
// MIN_VALUE - 1 wraps around to MAX_VALUE, a positive number.
System.out.println(bad.compare(Integer.MIN_VALUE, 1)); // 2147483647: claims MIN_VALUE > 1
System.out.println(good.compare(Integer.MIN_VALUE, 1)); // -1
List<Integer> xs = new ArrayList<>(List.of(1, Integer.MIN_VALUE, 0, Integer.MAX_VALUE));
xs.sort(good);
System.out.println(xs); // [-2147483648, 0, 1, 2147483647]
}
}Use Integer.compare, Long.compare, or Comparator.comparingInt. In JavaScript, x.p - y.p is safe for ordinary numbers because they are doubles and do not wrap. It still fails when a value is NaN or undefined, because the subtraction then returns NaN.
Floating-Point NaN
IEEE 754 says every comparison involving NaN is false. NaN is therefore "equivalent" to every number, while those numbers are not equivalent to each other. That breaks transitivity of equivalence. A list that contains NaN, sorted with plain <, can come out with the ordinary numbers in the wrong order around the NaN.
Rust makes this visible in the type system: f64 implements only PartialOrd, so v.sort() does not compile. You must pick a total order on purpose.
fn main() {
let mut v = vec![2.5, f64::NAN, -1.0, 0.0, -0.0];
v.sort_by(|a, b| a.total_cmp(b));
println!("{:?}", v); // [-1.0, -0.0, 0.0, 2.5, NaN]
}In Python you can do the same with a key that sends NaN to the end:
import math
values = [2.5, float("nan"), -1.0, 0.0]
print(sorted(values, key=lambda x: (math.isnan(x), x)))
# [-1.0, 0.0, 2.5, nan]Two NaN keys (True, nan) compare as equivalent, and every NaN key comes after every non-NaN key, so the four rules hold.
Tolerance Comparisons
Treating two floats as equal when they are "close enough" seems reasonable, but it is not transitive. With a tolerance of 0.06, 1.00 is equivalent to 1.05 and 1.05 is equivalent to 1.10, yet 1.00 comes before 1.10. The equal-key groups now overlap, and neither the sort nor its stability guarantee has a defined result. If you need buckets, map each value to a bucket explicitly in the key, for example round(x, 1). The buckets then have fixed edges that every comparison agrees on.
Random Comparators
arr.sort(() => Math.random() - 0.5) breaks asymmetry and determinism. It does not produce a uniform shuffle. Some permutations show up much more often than others, depending on the engine's algorithm. Use a Fisher–Yates shuffle instead.
Prefer Keys and Library Combinators
Most contract bugs come from hand-written comparison logic. Two habits avoid nearly all of them.
- Use a key function when the language offers one. Python's
key=, Rust'ssort_by_key, and Java'sComparator.comparingall delegate to the key type's built-in ordering. Built-in orderings on integers, strings and tuples are already strict weak orderings. - Compose comparators from library pieces. Java's
thenComparingandreversed(), Rust'sOrdering::then_with, C++'sstd::tie, and Python tuples as keys all build correct lexicographic orders from correct parts.
Checking a Comparator Mechanically
When you do write a comparator by hand, you can test it by brute force against a representative sample. The checker below tests all four rules on every pair and triple of the sample. It runs in cubic time, so keep the sample small, a few dozen values, but include edge cases such as duplicates, extremes and NaN.
import itertools
import math
def check_strict_weak_order(less, sample):
problems = []
equiv = lambda a, b: not less(a, b) and not less(b, a)
for a in sample:
if less(a, a):
problems.append(f"irreflexivity fails for {a!r}")
for a, b in itertools.permutations(sample, 2):
if less(a, b) and less(b, a):
problems.append(f"asymmetry fails for {a!r}, {b!r}")
for a, b, c in itertools.permutations(sample, 3):
if less(a, b) and less(b, c) and not less(a, c):
problems.append(f"transitivity fails for {a!r}, {b!r}, {c!r}")
if equiv(a, b) and equiv(b, c) and not equiv(a, c):
problems.append(f"equivalence not transitive for {a!r}, {b!r}, {c!r}")
return problems
floats = [1.0, 2.0, float("nan")]
print(len(check_strict_weak_order(lambda a, b: a < b, floats)) > 0) # True: NaN breaks it
near = lambda a, b: a < b and abs(a - b) > 0.06
print(check_strict_weak_order(near, [1.00, 1.05, 1.10])[:1])
# ['equivalence not transitive for 1.0, 1.05, 1.1']
nan_last = lambda a, b: (math.isnan(a), a) < (math.isnan(b), b)
print(check_strict_weak_order(nan_last, floats)) # []Exercise
A Go program sorts with sort.SliceStable(xs, func(i, j int) bool { return xs[i].Score <= xs[j].Score }). Which rule does this break, and what does it do to the stability guarantee?
Show answer
It breaks irreflexivity (and asymmetry for equal scores), because two elements with equal scores each report being "less" than the other. The sort no longer sees them as equivalent, so there is no well-defined group of equal keys whose input order could be preserved. The result order is unspecified. Using < fixes it and restores stable behavior.
Exercise
Write a Java comparator for record Task(String owner, long deadline) that orders by owner ascending and then by deadline descending, without any subtraction.
Show answer
Comparator.comparing(Task::owner).thenComparing(Comparator.comparingLong(Task::deadline).reversed()). comparingLong uses Long.compare internally, so it cannot overflow. reversed() flips only the deadline part.
Exercise
Prices are compared with "a is less than b if b - a > 0.01". Show three prices that violate transitivity of equivalence, and suggest a correct key.
Show answer
1.000, 1.008 and 1.016. The first two differ by 0.008 and so do the last two, so each neighboring pair is equivalent, but 1.016 - 1.000 = 0.016 > 0.01, so the first comes before the third. A correct approach is to sort on an exact quantity, for example the integer number of cents round(price * 100), or on the raw price if no bucketing is needed.