Conceptcore
Comparator
Also called comparison function, compare function, three-way comparison, key function, sort key, Comparator interface, cmp function, ordering function, collation function.
A comparator is a function that gets two values and tells which one comes first. A key function gets one value and returns the value to compare. Sorts, sorted maps and heaps use them.
- Applies to
- core-languages
Idea
A sort must know which of two items comes first. For numbers and text, the language has a default order. For other items, or for another order, the program gives the sort a function. There are two kinds of such functions. A comparator, also called a comparison function, gets two items and returns their order. A key function gets one item and returns a value, the sort key, and the sort compares the keys with the default order.
from functools import cmp_to_key
words = ["pear", "fig", "apple", "kiwi"]
# A key function maps one item to a value that Python compares.
print(sorted(words, key=len))
# A comparison function gets two items and returns a negative number, zero or a positive number.
def by_length_then_text(a, b):
if len(a) != len(b):
return len(a) - len(b)
return (a > b) - (a < b)
print(sorted(words, key=cmp_to_key(by_length_then_text)))
# The same order with a key: a tuple compares item by item.
print(sorted(words, key=lambda w: (len(w), w)))
['fig', 'pear', 'kiwi', 'apple']
['fig', 'kiwi', 'pear', 'apple']
['fig', 'kiwi', 'pear', 'apple']
The key len sorts the words by length. pear and kiwi have the same length, so they keep their old order. The comparison function by_length_then_text compares the lengths first and the text second, so kiwi comes before pear. cmp_to_key changes the comparison function into a key, because Python sorted() takes only a key. The tuple key (len(w), w) gives the same order as the comparison function, with less code.
How it works
The three-way contract. Most comparators return an integer whose sign is the answer. The Java compare method "Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second"1. Python uses the same rule: "A comparison function is any callable that accepts two arguments, compares them, and returns a negative number for less-than, zero for equality, or a positive number for greater-than"2. JavaScript, C and Go use it too345. In C#, the interface IComparer<T> "Defines a method that a type implements to compare two objects"6, and the delegate Comparison<T> "Represents the method that compares two objects of the same type"7. Both return an int with the same rule. Some languages return a special type instead of an integer. Rust returns an Ordering, and "An Ordering is the result of a comparison between two values"8. Haskell has the same type with the values LT, EQ and GT9. C++ <=> returns an ordering object, and "(a <=> b) < 0 if a < b"10.
The two-way contract. C++ uses a comparator that returns bool. The comparator "yields true if the first argument of the call appears before the second in the strict weak ordering relation induced by this type, and false otherwise"11. The sort calls it twice to find that two items are equal: when comp(a, b) and comp(b, a) are both false, the items are equivalent.
The rules of an order. A comparator must describe a consistent order, or the sort can give a wrong result. MDN lists the rules for a JavaScript compare function3:
| Rule | Meaning |
|---|---|
| pure | the comparator does not change its arguments and has no side effects |
| reflexive | an item compared with itself gives zero |
| anti-symmetric | if a comes before b, then b comes after a |
| transitive | if a comes before b and b comes before c, then a comes before c |
Java states the anti-symmetric rule as an equation: "The implementor must ensure that signum(compare(x, y)) == -signum(compare(y, x)) for all x and y"1. For C++ bool comparators, the rules are "For all a, comp(a, a) == false. If comp(a, b) == true then comp(b, a) == false"11. A comparator that breaks a rule does not always cause an error. Rust says that if the function "does not implement a total order, the function may panic; even if the function exits normally, the resulting order of elements in the slice is unspecified"12.
Key functions. A key function is shorter and harder to get wrong. The Python glossary says: "A key function or collation function is a callable that returns a value used for sorting or ordering"13. The key must have a default order, for example a number, a string or a tuple. The Python HOWTO gives the difference between the two kinds: "Unlike key functions that return an absolute value for sorting, a comparison function computes the relative ordering for two inputs"14. Rust sort_by_key "Sorts the slice in ascending order with a key extraction function"12, and Java Comparator.comparing "Accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator that compares by that sort key"1.
Natural order. A type can have one built-in order. In Java, the interface Comparable "imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering"15. A Comparator is a separate object that gives another order, for example by name instead of by date. Rust has the same split: the trait Ord is for "types that form a total order"16, and sort_by takes any other order. Haskell has the class Ord, which "is used for totally ordered datatypes"9, and sortBy, which takes a function.
Composition. Libraries have functions that build a comparator from smaller parts:
| Operation | Java | Rust | Go | Python | Haskell |
|---|---|---|---|---|---|
| order by a key | comparing(f) |
sort_by_key(f) |
cmp.Compare(f(a), f(b)) |
key=f |
comparing f |
| then by another key | thenComparing(g) |
then_with(g) |
cmp.Or(c1, c2) |
tuple key | <> on Ordering |
| reverse the order | reversed() |
Reverse(k) or .reverse() |
swap a and b |
reverse=True |
Down k |
| put nulls first | nullsFirst(c) |
Option order |
not in the library | not in the library | Maybe order |
Java thenComparing "Returns a lexicographic-order comparator with another comparator"1. Rust then "Chains two orderings. Returns self when it’s not Equal. Otherwise returns other"8. Go cmp.Or "returns the first of its arguments that is not equal to the zero value"5, so a zero from the first comparison passes to the second. Haskell defines comparing p x y = compare (p x) (p y)9, the comparator of a key function in one line.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the JavaScript compare function, and its type is (a, b) => number. A function that returns a boolean does not match that type, so the compiler finds the error that JavaScript does not find. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has the Java interfaces Comparator and Comparable, and the functions compareBy, thenBy and reversed build comparators from keys. sortedWith takes a comparator and sortedBy takes a key. No example file exists because kotlinc is not installed. |
| SQL | Native | ORDER BY takes a list of key expressions, each with ASC or DESC and optional NULLS FIRST or NULLS LAST. COLLATE selects the order of text. A query cannot give a compare function of two rows. No example file exists. |
| Bash | Idiom | Bash cannot give a function to a sort. The sort command takes keys and options instead, for example -k for a field, -n for numbers, -r for the reverse order and -t for the field separator. No example file exists. |
| PowerShell | Native | Sort-Object takes properties or script blocks as keys, and a hash table with Expression and Descending sets the direction of each key. The .NET method [Array]::Sort takes a Comparison delegate. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup. It has no functions that order values. |
| CSS | Does not apply | CSS has no functions that compare values. The order property takes an integer for each flex or grid item, not a comparator. |
| Regular expressions | Does not apply | A regular expression matches text. It does not compare two values or order them. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | key= on sort, sorted, min, max; functools.cmp_to_key changes a comparison function into a key |
| JavaScript | native | a compare function (a, b) => number for sort and toSorted; Intl.Collator and localeCompare for text |
| TypeScript | native | the JavaScript compare function, with the type (a: T, b: T) => number |
| Java | native | Comparator<T> and Comparable<T>; comparing, thenComparing, reversed, nullsFirst |
| Kotlin | native | Comparator<T> and Comparable<T>; compareBy, thenBy, sortedWith and sortedBy |
| C# | native | IComparer<T>, Comparison<T> and IComparable<T>; LINQ OrderBy and ThenBy take keys |
| Go | native | func(a, b T) int for slices.SortFunc; cmp.Compare and cmp.Or |
| Rust | native | the traits Ord and PartialOrd; Ordering; sort_by, sort_by_key, then_with, Reverse |
| C | native | a function pointer int (*)(const void *, const void *) for qsort and bsearch |
| C++ | native | a bool comparator for a strict weak ordering; <=> returns an ordering object; ranges take projections |
| Bash | idiom | the sort command takes keys and options (-k, -n, -r, -t), not a function |
| PowerShell | native | Sort-Object takes properties or script blocks as keys; [Array]::Sort takes a .NET Comparison |
| SQL | native | ORDER BY takes key expressions with ASC, DESC and NULLS FIRST; COLLATE selects a text order |
| Regex | n/a | a pattern matches text and does not order values |
| HTML | n/a | markup does not order values |
| CSS | n/a | the style rules do not order values; the order property takes a number, not a function |
Every general-purpose language in the table accepts a function that orders two values. The languages differ in the return type (an integer, a bool or an ordering type), in the support for key functions, and in the helpers that build a comparator from keys.
The example files show these differences. Python shows tuple keys, a minus sign that reverses one key, a comparator that returns bool and gives a wrong order, and the error for the old cmp argument. JavaScript shows the default text order, chained keys with || and Intl.Collator. Java shows comparingInt, thenComparing, reversed, nullsFirst and a comparator a - b that overflows. C# shows Comparison<T>, ThenBy and Comparer<T>.Create for a SortedSet. Go shows cmp.Compare, cmp.Or and the order of NaN. Rust shows then_with, Reverse, total_cmp for floats and partial_cmp. C shows the three-way idiom for qsort and a comparator for strings. C++ shows a bool comparator, std::tie, a projection and a defaulted <=>.
from functools import cmp_to_key
people = [("ann", 31), ("bob", 25), ("cy", 31), ("di", 25)]
# A tuple key sorts by several fields: age first, then name.
print(sorted(people, key=lambda p: (p[1], p[0])))
# reverse=True turns the whole order around.
print(sorted(people, key=lambda p: p[1], reverse=True))
# A minus sign reverses one numeric field and keeps the other ascending.
print(sorted(people, key=lambda p: (-p[1], p[0])))
# A comparison that returns a bool is wrong: False is 0, so "less" never happens.
nums = [3, 1, 2, 5, 4]
print(sorted(nums, key=cmp_to_key(lambda a, b: a > b)))
# The correct three-way form returns -1, 0 or 1.
print(sorted(nums, key=cmp_to_key(lambda a, b: (a > b) - (a < b))))
# Python 3 has no cmp argument.
try:
sorted(nums, cmp=lambda a, b: a - b)
except TypeError as e:
print(type(e).__name__)
[('bob', 25), ('di', 25), ('ann', 31), ('cy', 31)]
[('ann', 31), ('cy', 31), ('bob', 25), ('di', 25)]
[('ann', 31), ('cy', 31), ('bob', 25), ('di', 25)]
[3, 1, 2, 5, 4]
[1, 2, 3, 4, 5]
TypeError
- Verdict: native. A tuple key sorts by several fields, and a minus sign reverses one numeric field.
reverse=Truereverses the whole order and keeps equal items in their old order. A comparison function that returnsa > bnever gives a negative number, socmp_to_keywith it leaves the list in a wrong order. The three-way form(a > b) - (a < b)sorts the list.sortedhas nocmpargument, so the call raisesTypeError.
#include <algorithm>
#include <compare>
#include <functional>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
struct Person {
std::string name;
int age;
// A defaulted <=> compares the members in order: name, then age.
auto operator<=>(const Person &) const = default;
};
static void show(const std::vector<Person> &v) {
for (const auto &p : v) std::cout << p.name << ' ';
std::cout << '\n';
}
int main() {
std::vector<Person> people{{"cy", 31}, {"ann", 31}, {"bob", 25}};
// A C++ comparator returns bool: true when the first argument goes first.
auto byAge = [](const Person &a, const Person &b) { return a.age < b.age; };
std::ranges::stable_sort(people, byAge);
show(people);
// std::tie compares several keys in order.
std::ranges::sort(people, [](const Person &a, const Person &b) {
return std::tie(a.age, a.name) < std::tie(b.age, b.name);
});
show(people);
// A projection gives a key; std::ranges::greater reverses the order.
std::ranges::sort(people, std::ranges::greater{}, &Person::age);
std::cout << people.front().age << ' ' << people.back().age << '\n';
// The defaulted <=> gives the natural order of the struct.
std::ranges::sort(people);
show(people);
// <=> returns an ordering object, not a number.
auto r = 1 <=> 2;
std::cout << (r < 0) << ' ' << (r == std::strong_ordering::less) << '\n';
}
bob cy ann
bob ann cy
31 25
ann bob cy
1 1
- Verdict: native. A C++ comparator returns
bool.stable_sortby age keepscybeforeann.std::tiecompares the age and then the name. A projection&Person::agewithstd::ranges::greatersorts by age in descending order. A defaulted<=>gives the natural order by name, and1 <=> 2is an ordering object that compares less than zero.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Main {
record Person(String name, int age) {}
public static void main(String[] args) {
List<Person> people = List.of(
new Person("cy", 31), new Person("ann", 31), new Person("bob", 25));
// Comparator.comparing makes a comparator from a key; thenComparing adds a second key.
Comparator<Person> byAgeThenName =
Comparator.comparingInt(Person::age).thenComparing(Person::name);
System.out.println(people.stream().sorted(byAgeThenName).map(Person::name).toList());
// reversed() turns the whole comparator around.
System.out.println(people.stream().sorted(byAgeThenName.reversed()).map(Person::name).toList());
// A lambda can implement compare directly; Integer.compare gives -1, 0 or 1.
Comparator<Person> byAge = (a, b) -> Integer.compare(a.age(), b.age());
System.out.println(byAge.compare(people.get(0), people.get(2)));
// Subtraction overflows: MIN_VALUE - 1 wraps to MAX_VALUE, so the order is wrong.
Integer[] nums = {1, Integer.MIN_VALUE, 0};
Arrays.sort(nums, (a, b) -> a - b);
System.out.println(Arrays.toString(nums));
Arrays.sort(nums, Integer::compare);
System.out.println(Arrays.toString(nums));
// nullsFirst wraps a comparator so that null items do not throw.
List<String> names = new ArrayList<>(Arrays.asList("b", null, "a"));
names.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
System.out.println(names);
}
}
[bob, ann, cy]
[cy, ann, bob]
1
[0, 1, -2147483648]
[-2147483648, 0, 1]
[null, a, b]
- Verdict: native.
comparingIntandthenComparingbuild a comparator from two keys, andreversedturns it around.Integer.comparegives -1, 0 or 1. The comparatora - boverflows forInteger.MIN_VALUE - 1, so the first sort putsMIN_VALUElast.nullsFirstputsnullbefore the other items instead of throwingNullPointerException.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* The three-way idiom: (x > y) - (x < y) is -1, 0 or 1 and cannot overflow. */
static int ascending(const void *a, const void *b) {
int x = *(const int *)a, y = *(const int *)b;
return (x > y) - (x < y);
}
/* Swap the operands to sort in descending order. */
static int descending(const void *a, const void *b) {
return ascending(b, a);
}
/* qsort passes pointers to the items, so for strings it passes char **. */
static int by_text(const void *a, const void *b) {
return strcmp(*(const char *const *)a, *(const char *const *)b);
}
static void show(const int *a, size_t n) {
for (size_t i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
}
int main(void) {
int nums[] = {3, 1, 2};
qsort(nums, 3, sizeof nums[0], ascending);
show(nums, 3);
qsort(nums, 3, sizeof nums[0], descending);
show(nums, 3);
const char *words[] = {"pear", "fig", "apple"};
qsort(words, 3, sizeof words[0], by_text);
printf("%s %s %s\n", words[0], words[1], words[2]);
/* INT_MIN - 1 does not fit in an int, and signed overflow is undefined behavior,
so a comparator must not return x - y. The three-way idiom gives -1. */
long long wide = (long long)INT_MIN - 1;
printf("%lld %d\n", wide, ascending(&(int){INT_MIN}, &(int){1}));
return 0;
}
1 2 3
3 2 1
apple fig pear
-2147483649 -1
- Verdict: native.
qsorttakes a pointer to a function that returns a negative, zero or positiveint.(x > y) - (x < y)gives -1, 0 or 1 and cannot overflow, and the descending comparator swaps its arguments. For an array of strings,qsortpasses pointers to thechar *items.INT_MIN - 1does not fit in anint, so the program shows the value in along long.
using System;
using System.Collections.Generic;
using System.Linq;
var people = new List<(string Name, int Age)> { ("cy", 31), ("ann", 31), ("bob", 25) };
// A Comparison<T> delegate returns a negative number, zero or a positive number.
Comparison<int> ascending = (a, b) => a.CompareTo(b);
Console.WriteLine($"{ascending(25, 31)} {ascending(31, 31)} {ascending(31, 25)}");
// Chain two keys: use the second key when the first gives zero.
var byAgeThenName = people.ToList();
byAgeThenName.Sort((a, b) =>
{
int c = a.Age.CompareTo(b.Age);
return c != 0 ? c : string.CompareOrdinal(a.Name, b.Name);
});
Console.WriteLine(string.Join(",", byAgeThenName.Select(p => p.Name)));
// LINQ takes keys instead: OrderBy, then ThenBy.
Console.WriteLine(string.Join(",", people.OrderByDescending(p => p.Age).ThenBy(p => p.Name, StringComparer.Ordinal).Select(p => p.Name)));
// Comparer<T>.Create turns a lambda into an IComparer<T> for a sorted collection.
var reverse = Comparer<int>.Create((a, b) => b.CompareTo(a));
var set = new SortedSet<int>(new[] { 2, 3, 1 }, reverse);
Console.WriteLine(string.Join(",", set));
// Subtraction overflows for large values.
int x = int.MinValue, y = 1;
Console.WriteLine($"{unchecked(x - y)} {x.CompareTo(y)}");
-1 0 1
bob,ann,cy
ann,cy,bob
3,2,1
2147483647 -1
- Verdict: native. A
Comparison<int>delegate returns -1, 0 or 1.List<T>.Sorttakes a comparison that uses the name when the ages are equal. LINQOrderByDescendingandThenBytake keys instead.Comparer<int>.Createmakes anIComparer<int>that reverses the order of aSortedSet.int.MinValue - 1wraps toint.MaxValuein an unchecked context, andCompareTogives the correct sign.
// A compare function returns a negative number, zero or a positive number.
console.log([10, 9, 1].toSorted((a, b) => a - b));
// Without one, sort compares the items as strings.
console.log([10, 9, 1].toSorted());
// A compare function that returns a boolean never says "less".
console.log([3, 1, 2, 5, 4].toSorted((a, b) => a > b));
// Chain two keys with ||: a zero from the first key falls through to the second.
const people = [
{ name: "cy", age: 31 },
{ name: "ann", age: 31 },
{ name: "bob", age: 25 },
];
const byAgeThenName = (a, b) => a.age - b.age || a.name.localeCompare(b.name);
console.log(people.toSorted(byAgeThenName).map((p) => p.name));
// Swap the arguments to reverse the order.
console.log(people.toSorted((a, b) => byAgeThenName(b, a)).map((p) => p.name));
// Intl.Collator gives a compare function for text.
const collator = new Intl.Collator("en", { numeric: true });
console.log(["item10", "item9", "item1"].toSorted(collator.compare));
[ 1, 9, 10 ]
[ 1, 10, 9 ]
[ 3, 1, 2, 5, 4 ]
[ 'bob', 'ann', 'cy' ]
[ 'cy', 'ann', 'bob' ]
[ 'item1', 'item9', 'item10' ]
- Verdict: native.
(a, b) => a - bsorts numbers. Without a compare function,toSortedcompares the items as strings, so10comes before9. A compare function that returns a boolean gives a wrong order and no error.||passes a zero from the age to the name, and swapped arguments reverse the order.Intl.Collatorwithnumeric: trueputsitem9beforeitem10.
package main
import (
"cmp"
"fmt"
"math"
"slices"
"strings"
)
type person struct {
name string
age int
}
func main() {
// cmp.Compare returns -1, 0 or +1.
fmt.Println(cmp.Compare(1, 2), cmp.Compare(2, 2), cmp.Compare("b", "a"))
people := []person{{"cy", 31}, {"ann", 31}, {"bob", 25}}
// slices.SortFunc takes a three-way compare function; cmp.Or chains the keys.
slices.SortFunc(people, func(a, b person) int {
return cmp.Or(cmp.Compare(a.age, b.age), strings.Compare(a.name, b.name))
})
fmt.Println(people)
// Swap a and b to sort in descending order.
slices.SortFunc(people, func(a, b person) int { return cmp.Compare(b.age, a.age) })
fmt.Println(people[0].age, people[2].age)
// cmp.Compare puts NaN before other numbers, so floats sort in a total order.
fs := []float64{2, math.NaN(), 1}
slices.SortFunc(fs, cmp.Compare[float64])
fmt.Println(fs)
// SortStableFunc keeps equal items in their old order.
words := []string{"bb", "a", "cc", "d"}
slices.SortStableFunc(words, func(a, b string) int { return cmp.Compare(len(a), len(b)) })
fmt.Println(words)
}
-1 0 1
[{bob 25} {ann 31} {cy 31}]
31 25
[NaN 1 2]
[a d bb cc]
- Verdict: native.
cmp.Comparereturns -1, 0 or +1.slices.SortFunctakes a three-way function, andcmp.Oruses the name when the ages are equal. Swapped arguments sort in descending order.cmp.CompareputsNaNbefore the other floats.slices.SortStableFunckeepsbbbeforeccandabefored.
use std::cmp::{Ordering, Reverse};
fn main() {
// cmp returns an Ordering: Less, Equal or Greater.
println!("{:?} {:?} {:?}", 1.cmp(&2), 2.cmp(&2), "b".cmp("a"));
let mut people = vec![("cy", 31), ("ann", 31), ("bob", 25)];
// sort_by takes a compare function; then_with adds a second key.
people.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(b.0)));
println!("{:?}", people);
// sort_by_key takes a key; Reverse turns the order of one key around.
people.sort_by_key(|p| (Reverse(p.1), p.0));
println!("{:?}", people);
// f64 is not Ord, because NaN has no place in a total order. total_cmp gives one.
let mut fs = vec![2.0, f64::NAN, 1.0, -0.0, 0.0];
fs.sort_by(|a, b| a.total_cmp(b));
println!("{:?}", fs);
// partial_cmp returns None for NaN.
println!("{:?} {:?}", 1.0f64.partial_cmp(&2.0), f64::NAN.partial_cmp(&1.0));
// reverse() on an Ordering swaps Less and Greater.
let mut nums = vec![3, 1, 2];
nums.sort_by(|a, b| a.cmp(b).reverse());
println!("{:?} {:?}", nums, Ordering::Less.reverse());
}
Less Equal Greater
[("bob", 25), ("ann", 31), ("cy", 31)]
[("ann", 31), ("cy", 31), ("bob", 25)]
[-0.0, 0.0, 1.0, 2.0, NaN]
Some(Less) None
[3, 2, 1] Greater
- Verdict: native.
cmpreturns anOrdering.sort_bywiththen_withsorts by age and then by name, andsort_by_keywithReversesorts by age in descending order.f64is notOrd, so the program usestotal_cmp, which puts-0.0before0.0andNaNlast.partial_cmpreturnsNoneforNaN.reverseon anOrderingswapsLessandGreater.
Variations and related ideas
- Key functions as comparators. Every key function gives a comparator: compare the keys of the two items. The opposite is not always simple, and Python
cmp_to_keydoes it with a wrapper object: it will "Transform an old-style comparison function to a key function"2. - Decorate, sort, undecorate. A sort calls a comparator many times for each item, so a key that is slow to compute costs much. A program can compute each key once and sort the pairs of key and item. Haskell
sortOndoes this, and its documentation says that it has "the performance advantage of only evaluating f once for each element in the input list"17. - Collation. Text order depends on the language of the text. A collator, for example
Intl.Collatorin JavaScript orjava.text.Collatorin Java, is a comparator for the text of one locale. See compare strings. - Ordered collections. A sorted map, a sorted set and a priority queue keep their items in the order of a comparator. C#
Comparer<T>.Create"Creates a comparer by using the specified comparison"18 for such a collection. - Consistency with equality. Java says: "It is strongly recommended (though not required) that natural orderings be consistent with equals"15. If
compare(a, b)is zero buta.equals(b)is false, a sorted set keeps only one of the two items. See value equality and identity. - Partial orders. Some values have no order. Rust
partial_cmpreturnsNoneforNaN, and a sort of floats must usetotal_cmpor handleNaNin another way.
Pitfalls
- Subtraction overflows.
(a, b) -> a - bin Java or C# gives a wrong sign when the difference does not fit in anint. In C, signed overflow is undefined behavior. UseInteger.compare,CompareTo,cmp.Compareor(x > y) - (x < y). In JavaScript, MDN says that "(a, b) => a - b sorts numbers in ascending order"3, because JavaScript numbers are floating point and do not overflow in this way. - A comparator that returns a bool. A JavaScript or Python comparator that returns
a > bgivestrueorfalse, which convert to 1 or 0, never to a negative number. The sort then gives a wrong order and no error. C++ is the opposite: its comparators must returnbool, and a comparator that uses<=breaks the rules. - No compare function in JavaScript. Without a compare function,
sort()converts the items to strings, so[10, 9, 1].sort()gives[1, 10, 9]. - Inconsistent comparators. A comparator that uses random numbers, a clock or changing state breaks the rules. The Java sorts can throw
IllegalArgumentExceptionwhen they find such a comparator, and other sorts give a wrong order with no error. - NaN.
NaNis not less than, equal to or greater than any number. A comparator that uses<on floats is not transitive when the list holdsNaN. Gocmp.CompareputsNaNfirst: "a NaN is considered less than any non-NaN"5. - Null values. A Java comparator that calls a method on its argument throws
NullPointerExceptionfor anullitem. JavanullsFirst"Returns a null-friendly comparator that considers null to be less than non-null"1. - Unstable sorts. A comparator that returns zero for two items does not fix their order. Go says of
SortFunc: "This sort is not guaranteed to be stable"19. Use a stable sort or add a key that tells the items apart.
Cost
A comparison sort of n items calls the comparator about n log n times, so the cost of one call is multiplied by that number. A key function is called once for each item when the library computes the keys first. Python does this, and its sort is fast "because the key function is called exactly once for each input record"14. A comparator that computes keys inside itself computes each key about 2 log n times. A comparator that calls other comparators in a chain stops at the first non-zero result, so the later keys cost time only for items that are equal on the earlier keys. A call through a function pointer, as in C qsort, is not inlined, and C++ std::sort with a lambda is often faster for that reason.
History
The C library qsort takes "comparison function which returns" a negative, zero or positive integer4, and later libraries kept the three-way contract. Java added the interfaces Comparator and Comparable together with its collections framework115.
Python first had both a cmp argument and a key argument on its sorts. The Python 3.0 release notes say: "sorted() and list.sort() no longer accept the cmp argument providing a comparison function. Use the key argument instead"20. The helper functools.cmp_to_key converts old comparison functions2. Newer libraries also prefer keys and composition: Rust has sort_by_key and then_with128, Go has cmp.Or5, and C++ has the three-way operator <=> and range projections10.
References
- Interface Comparator, Java SE 25 API, Description; compare; comparing; thenComparing; nullsFirst
- functools, Python documentation, cmp_to_key
- Array.prototype.sort(), MDN Web Docs, Parameters; Description
- qsort, qsort_s, C reference, cppreference.com, Parameters
- Package cmp, Go standard library, Compare; Or
- IComparer<T> Interface, .NET API reference, Definition
- Comparison<T> Delegate, .NET API reference, Definition
- Enum Ordering, The Rust Standard Library, Description; then
- Data.Ord, Haskell base library, Ord; Ordering; comparing
- Comparison operators, C++ reference, cppreference.com, Three-way comparison
- C++ named requirements, Compare, cppreference.com, Requirements
- Primitive Type slice, The Rust Standard Library, sort_by; sort_by_key
- Glossary, Python documentation, key function
- Sorting Techniques, Python documentation, Comparison Functions
- Interface Comparable, Java SE 25 API, Description
- Trait Ord, The Rust Standard Library, Description
- Data.List, Haskell base library, sortBy; sortOn
- Comparer<T>.Create(Comparison<T>) Method, .NET API reference, Definition
- Package slices, Go standard library, SortFunc
- What's New In Python 3.0, Python documentation, Ordering Comparisons
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 2ZWRWS Edit this page History Report an error Markdown