Sub topic 8
Writing Comparators the Library Can Trust
This chapter assumes you can pass a comparator or key function to a sort, and that you know how equal keys behave under a stable sort. A sort routine treats your comparator as ground truth. If the comparator breaks the rules the library relies on, the result is not a slightly wrong order. You can get garbage output, an exception, or in C++ undefined behavior, including crashes.
The contract: strict weak ordering
Most libraries require a strict weak ordering. For a "less than" function less(a, b), the rules are:
| Rule | Meaning |
|---|---|
| Irreflexive | `less(a, a)` is always false |
| Asymmetric | if `less(a, b)` then not `less(b, a)` |
| Transitive | `less(a, b)` and `less(b, c)` imply `less(a, c)` |
| Transitive equivalence | if `a` ~ `b` and `b` ~ `c` (neither is less), then `a` ~ `c` |
The last rule is what makes "equal elements" a well-defined group. Stability is defined over those groups, so a comparator that breaks this rule makes stability meaningless.
Three-way comparators, such as Java's compare or JavaScript's comparison function, must follow the same rules. Their result must also be consistent: sign(compare(a, b)) == -sign(compare(b, a)), and the answer must not change during the sort.
Common errors
Using `<=` instead of `<` in C++
[](int a, int b) { return a <= b; } returns true for less(a, a), which breaks irreflexivity. With std::sort this is undefined behavior. Some implementations read past the end of the array when many keys are equal. Always use strict <, and use std::tie to compare several fields:
#include <algorithm>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
struct Row { std::string last; int age; };
int main() {
std::vector<Row> rows = {{"lee", 40}, {"kim", 31}, {"lee", 22}};
std::sort(rows.begin(), rows.end(), [](const Row& x, const Row& y) {
return std::tie(x.last, x.age) < std::tie(y.last, y.age); // strict, lexicographic
});
for (const auto& r : rows) std::cout << r.last << ' ' << r.age << '\n';
}Subtraction in Java comparators
(a, b) -> a - b overflows when the values are far apart, so the sign comes out wrong.
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Comparator<Integer> bad = (a, b) -> a - b;
Comparator<Integer> good = Integer::compare;
int a = Integer.MIN_VALUE, b = 1;
System.out.println(bad.compare(a, b)); // positive: claims MIN_VALUE > 1
System.out.println(good.compare(a, b)); // -1
}
}Java's TimSort sometimes detects a broken comparator and throws IllegalArgumentException: Comparison method violates its general contract!. That exception means the comparator is at fault. The sort is working as designed.
Booleans in JavaScript comparators
arr.sort((x, y) => x > y) returns true or false, which JavaScript converts to 1 or 0. The comparator never returns a negative number, so it breaks asymmetry. Return x - y for finite numbers, or use localeCompare for strings.
NaN and other incomparable values
In IEEE floating point, every comparison involving NaN is false. That makes NaN "equivalent" to every number, which breaks transitive equivalence. Give such values an explicit position:
import math
data = [3.0, float("nan"), 1.0, 2.0]
print(sorted(data)) # order not guaranteed to be sorted
print(sorted(data, key=lambda x: (math.isnan(x), x))) # [1.0, 2.0, 3.0, nan]Keys that change during the sort
A comparator that reads mutable state, calls a random number generator, or depends on the current time can give different answers for the same pair. Compute the keys once before sorting, which is what Python's key= does for you.
Exercise
A Java comparator for prices stored as double is written as (a, b) -> (int) (a.price - b.price). Name two ways it breaks the contract and give a fix.
Show answer
The cast truncates, so prices that differ by less than 1 compare as equal. That breaks transitive equivalence: 1.0 ~ 1.6 and 1.6 ~ 2.2, but 1.0 < 2.2. Large differences can also overflow the int cast and give the wrong sign. Fix: Comparator.comparingDouble(p -> p.price), which uses Double.compare and also gives NaN a consistent position.
Exercise
Why is [](int a, int b) { return a <= b; } dangerous with std::sort but would not cause the same problem as a Python key function?
Show answer
It returns true for less(a, a), which breaks irreflexivity and is undefined behavior in std::sort. A Python key function returns a value, and Python's own < on that value is used, so there is no user-written "less than" to get wrong.