Conceptcore
Natural ordering
Also called natural order, Comparable, Ord trait, IComparable, rich comparisons, __lt__, spaceship operator, default ordering.
The natural ordering of a type is the default order that the type defines for its values, such as Java's compareTo or Rust's Ord, which sorts and sorted collections use when no other order is given.
- Applies to
- core-languages
Idea
Many types have one order that most code expects: numbers from small to large, strings in dictionary order, dates from early to late. A type that defines this order for its own values gives it a natural ordering. Java's Comparable says: "This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering".1 Sorting, sorted sets, sorted maps, min and max then work on the type with no extra argument.
A type has at most one natural ordering. Other orders, such as "by price" or "newest first", are separate comparison functions that a caller passes in, which is the job of a comparator.
How it works
A natural ordering is a method that compares this object with another object of the same type. It has one of two forms.
- A three-way comparison returns a negative number, zero or a positive number, or an enum such as Rust's
Ordering. Java'scompareTo, C#'sCompareTo, Go'scmp.Compareand C++'soperator<=>use this form. Go'sCompare"returns -1 if x is less than y, 0 if x equals y, +1 if x is greater than y."2 - A less-than method answers one question. Python's rich comparisons map each operator to a method: "x<y calls x.lt(y)".3
functools.total_orderingwrites the rest: "Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest."4
For a type with several fields, the usual order is lexicographic: compare the most important field, and compare the next field only when the first fields are equal. Rust's derived Ord does this: "When derived on structs, it will produce a lexicographic ordering based on the top-to-bottom declaration order of the struct’s members."5
The method must define a real order, or a sort can give wrong results. Rust states the rules for Ord: for all values, "exactly one of a < b, a == b or a > b is true; and < is transitive".5 This is a total order, "a partial order in which any two elements are comparable."6 Java adds one more rule that is strongly recommended, but not required: the order should be consistent with equals, which means that "e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2)".1
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Absent | C has no methods; qsort and bsearch take a comparison function that returns a negative number, zero or a positive number. |
| C# | Native | |
| JavaScript | Absent | |
| TypeScript | Absent | As JavaScript; objects have no natural order, and sort needs a comparison function; no example file because it would repeat the JavaScript answer. |
| Go | Idiom | |
| Rust | Standard library | |
| Kotlin | Native | A class implements Comparable<T>, and the operators <, <=, > and >= call compareTo; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | ORDER BY orders rows by column values; rows have no user methods. |
| Bash | Does not apply | Bash has no user types; sort and the [[ < ]] test compare strings. |
| PowerShell | Native | PowerShell objects are .NET objects, and a type can implement IComparable; no example file because it would repeat the C# answer. |
| HTML | Does not apply | HTML has no values to order. |
| CSS | Does not apply | CSS has no values to order. |
| Regular expressions | Does not apply | Regular expressions have no values to order. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | __lt__, __le__, __gt__, __ge__; functools.total_ordering; sorted uses < |
| JavaScript | absent | no natural order for objects; sort without a function compares strings |
| TypeScript | absent | as JavaScript |
| Java | native | Comparable<T>.compareTo; Comparator<T> for other orders |
| Kotlin | native | Comparable<T>.compareTo, and the operators < and > call it |
| C# | native | IComparable<T>.CompareTo; IComparer<T> for other orders |
| Go | idiom | a Compare method by convention; cmp.Ordered covers built-in types only |
| Rust | stdlib | traits PartialOrd and Ord, derivable; Ordering enum |
| C | absent | a comparison function passed to qsort and bsearch |
| C++ | native | operator<=>, which a class can default; operator< for older code |
| Bash | n/a | sort and [[ < ]] compare strings; no user types |
| PowerShell | native | .NET objects that implement IComparable |
| SQL | n/a | ORDER BY orders rows by column values; no user methods |
| Regex | n/a | no values to order |
| HTML | n/a | no values to order |
| CSS | n/a | no values to order |
- Java and C# keep the natural ordering on the type and other orders outside it.
Comparatoris "A comparison function, which imposes a total ordering on some collection of objects."7 In C#,CompareToreturns less than zero when "This object precedes the object specified by the CompareTo method in the sort order."8 - Rust splits the order into two traits.
PartialOrdallows values that cannot be compared, andOrdis the "Trait for types that form a total order."5 Floats are onlyPartialOrd, soVec<f64>::sortdoes not compile. - C++ can default the three-way comparison, and the compiler rewrites
<,<=,>and>=to use it. The result type gives the strength of the order: "There are three comparison category types: std::strong_ordering std::weak_ordering std::partial_ordering".9 - JavaScript has no hook for objects. "If compareFn is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings".10 Code passes a comparison function to every sort.
- Go has no operator overloading, so
<works only on built-in ordered types. A struct gets an order from aComparemethod, which code passes toslices.SortFunc.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major, minor):
self.major, self.minor = major, minor
def _key(self):
return (self.major, self.minor)
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self._key() == other._key()
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self._key() < other._key()
def __hash__(self):
return hash(self._key())
def __repr__(self):
return f"{self.major}.{self.minor}"
vs = [Version(1, 10), Version(1, 2), Version(0, 9)]
print(sorted(vs), Version(1, 2) >= Version(1, 2))
print(sorted(vs, key=lambda v: v.minor))
try:
Version(1, 0) < "1.0"
except TypeError as e:
print("TypeError:", e)
[0.9, 1.2, 1.10] True
[1.2, 0.9, 1.10]
TypeError: '<' not supported between instances of 'Version' and 'str'
- Verdict: native. The rich comparison methods
__lt__,__le__,__gt__and__ge__give a class its order, andsortedandlist.sortuse<. functools.total_orderingwrites the other three methods from__eq__and__lt__. Comparing tuples of the fields gives a lexicographic order with no extra code.- A
keyfunction gives a different order without a change to the class. When both methods returnNotImplemented, Python raisesTypeError, so aVersionand a string are not ordered.
#include <algorithm>
#include <compare>
#include <iostream>
#include <limits>
#include <vector>
struct Version {
int major;
int minor;
auto operator<=>(const Version&) const = default;
};
int main() {
std::vector<Version> vs{{1, 10}, {1, 2}, {0, 9}};
std::sort(vs.begin(), vs.end());
for (std::size_t i = 0; i < vs.size(); ++i) {
std::cout << (i ? " " : "") << vs[i].major << '.' << vs[i].minor;
}
std::cout << '\n';
auto c = Version{1, 2} <=> Version{1, 10};
std::cout << (c < 0) << ' ' << (Version{1, 2} == Version{1, 2}) << '\n';
double nan = std::numeric_limits<double>::quiet_NaN();
auto f = 1.0 <=> nan;
std::cout << (f == std::partial_ordering::unordered) << '\n';
}
0.9 1.2 1.10
1 1
1
- Verdict: native. A class can default
operator<=>, which compares the members in the order of their declaration, and the compiler then rewrites<,<=,>and>=to use it. - A defaulted
operator<=>also declares a defaultedoperator==, so==works with no more code. - The result type tells the strength of the order:
intmembers givestd::strong_ordering, anddoublegivesstd::partial_ordering, where aNaNcompares asunordered.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
record Version(int major, int minor) implements Comparable<Version> {
@Override
public int compareTo(Version o) {
int c = Integer.compare(major, o.major);
return c != 0 ? c : Integer.compare(minor, o.minor);
}
}
public static void main(String[] args) {
List<Version> vs = new ArrayList<>(List.of(new Version(1, 10), new Version(1, 2), new Version(0, 9)));
vs.sort(null);
System.out.println(vs);
vs.sort(Comparator.comparingInt(Version::minor).reversed());
System.out.println(vs);
}
}
[Version[major=0, minor=9], Version[major=1, minor=2], Version[major=1, minor=10]]
[Version[major=1, minor=10], Version[major=0, minor=9], Version[major=1, minor=2]]
- Verdict: native. A class that implements
Comparable<T>has a natural ordering, andlist.sort(null),Collections.sort,TreeSetandTreeMapuse it. compareTocompares the fields in order of importance withInteger.compare, which avoids the overflow ofa - b.- A
Comparatorgives another order.Comparator.comparingInt(Version::minor).reversed()sorts by the minor number, largest first.
using System;
using System.Collections.Generic;
var vs = new List<AppVersion> { new(1, 10), new(1, 2), new(0, 9) };
vs.Sort();
Console.WriteLine(string.Join(" ", vs));
vs.Sort((a, b) => b.Minor.CompareTo(a.Minor));
Console.WriteLine(string.Join(" ", vs));
Console.WriteLine(new AppVersion(1, 2).CompareTo(null));
sealed record AppVersion(int Major, int Minor) : IComparable<AppVersion>
{
// A null reference is less than any object.
public int CompareTo(AppVersion? other)
{
if (other is null) return 1;
int c = Major.CompareTo(other.Major);
return c != 0 ? c : Minor.CompareTo(other.Minor);
}
public override string ToString() => $"{Major}.{Minor}";
}
0.9 1.2 1.10
1.10 0.9 1.2
1
- Verdict: native. A type that implements
IComparable<T>has a default order, andList<T>.Sort,Array.SortandSortedSet<T>use it. CompareToreturns less than zero, zero or more than zero. By convention, any object is greater thannull, soCompareTo(null)returns a positive number.- A
Comparison<T>delegate or anIComparer<T>gives another order, here the minor number from largest to smallest.
console.log([10, 9, 1, 2].sort());
console.log([10, 9, 1, 2].sort((a, b) => a - b));
class Version {
constructor(major, minor) {
this.major = major;
this.minor = minor;
}
static compare(a, b) {
return a.major - b.major || a.minor - b.minor;
}
toString() {
return `${this.major}.${this.minor}`;
}
}
const vs = [new Version(1, 10), new Version(1, 2), new Version(0, 9)];
console.log(vs.sort(Version.compare).join(" "));
[ 1, 10, 2, 9 ]
[ 1, 2, 9, 10 ]
0.9 1.2 1.10
- Verdict: absent. JavaScript objects have no natural order, and
<on two objects compares their primitive values. - Without a comparison function,
sortconverts the items to strings and compares those, so10comes before2. - The usual idiom is a static
compare(a, b)that returns a negative number, zero or a positive number, passed tosort. The||moves to the next field when the first fields are equal.
package main
import (
"cmp"
"fmt"
"math"
"slices"
)
type Version struct{ Major, Minor int }
// Compare gives the natural order of Version by convention.
func (v Version) Compare(o Version) int {
return cmp.Or(cmp.Compare(v.Major, o.Major), cmp.Compare(v.Minor, o.Minor))
}
func main() {
vs := []Version{{1, 10}, {1, 2}, {0, 9}}
slices.SortFunc(vs, Version.Compare)
fmt.Println(vs)
xs := []float64{2, math.NaN(), -1}
slices.Sort(xs)
fmt.Println(xs, cmp.Compare(math.NaN(), math.NaN()), math.NaN() < 0)
}
[{0 9} {1 2} {1 10}]
[NaN -1 2] 0 false
- Verdict: idiom. The
<operator works only on ordered types, such as numbers and strings; a struct has no order. The convention is aComparemethod, whichslices.SortFunctakes as a function. cmp.Orreturns its first argument that is not zero, so it chains the comparisons of the fields.cmp.Compareandslices.SorttreatNaNas less than any other number and equal to itself, which gives floats a total order; the operator<still gives false forNaN.
use std::cmp::Ordering;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Version {
major: u32,
minor: u32,
}
fn main() {
let mut vs = vec![
Version { major: 1, minor: 10 },
Version { major: 1, minor: 2 },
Version { major: 0, minor: 9 },
];
vs.sort();
let s: Vec<String> = vs.iter().map(|v| format!("{}.{}", v.major, v.minor)).collect();
println!("{}", s.join(" "));
let nan = f64::NAN;
println!("{:?} {:?}", nan.partial_cmp(&1.0), 1.0f64.partial_cmp(&2.0));
let mut xs = vec![2.0, nan, -1.0];
xs.sort_by(|a: &f64, b| a.total_cmp(b));
println!("{:?} {:?}", xs, Ordering::Less.reverse());
}
0.9 1.2 1.10
None Some(Less)
[-1.0, 2.0, NaN] Greater
- Verdict: stdlib.
Ordis the trait of a total order andPartialOrdthe trait of a partial order.#[derive(PartialOrd, Ord)]compares the fields in the order of their declaration. Vec::sortneedsOrd.f64implements onlyPartialOrd:partial_cmpreturnsNoneforNaN, so a vector of floats needssort_bywithtotal_cmp.Orderingis an enum withLess,EqualandGreater, and methods such asreverseandthencombine comparisons.
Variations and related ideas
- Total, weak and partial orders. A total order compares every pair and gives zero only for equal values. A weak order allows different values to be equivalent, such as strings compared without regard to case. A partial order allows pairs that cannot be compared, such as floats with
NaN: Rust shows that forf64::NAN,a <= ais false.11 - Key functions. In place of a comparison, a sort can take a function that maps each item to a key with a natural order, such as a tuple of fields. Python's
sorted(..., key=...)works this way, andfunctools.cmp_to_keyturns an old comparison function into a key function.4 - Comparators. A comparator is an order that lives outside the type, so a type can have many. The natural ordering is the one that the type chooses as the default.
- Equality. The order and the equality and hashing contract must agree. When
compare(a, b)is zero exactly whenaequalsb, a sorted set and a hash set hold the same items.
Pitfalls
- An order that is not consistent with equals. Java's
BigDecimalis the example in the documentation. Its natural ordering "equates BigDecimal objects with equal numerical values and different representations (such as 4.0 and 4.00)", butequalsdoes not:1
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
BigDecimal a = new BigDecimal("4.0");
BigDecimal b = new BigDecimal("4.00");
System.out.println(a.equals(b) + " " + a.compareTo(b));
System.out.println(new HashSet<>(List.of(a, b)).size() + " " + new TreeSet<>(List.of(a, b)).size());
}
}
false 0
2 1
A hash set keeps both values and a tree set keeps one. Java warns that such sorted sets "behave "strangely"".1
- Subtraction as comparison.
return a.x - b.x;overflows when the values have different signs and are large, and the sign of the result is then wrong. UseInteger.compare,cmp.Compareor<=>. - An order that is not transitive. A comparison that uses a tolerance, such as "equal if the difference is less than 0.01", is not transitive. A sort can then give a wrong order.
NaNin the data. With floats,NaN < xandNaN > xare both false, so a comparison built from<treatsNaNas equal to every number. Use a total order for floats, such as Rust'stotal_cmpor Go'scmp.Compare, which considersNaN"less than any non-NaN".2- The default sort in JavaScript.
[10, 9, 1, 2].sort()gives[1, 10, 2, 9], because the items are compared as strings.
Cost
A comparison method is called O(n log n) times when a sort orders n items, and O(log n) times for each insertion or lookup in a balanced tree. Its own cost grows with the number of fields that it must read before two values differ. A three-way comparison costs one call for each step, while a less-than method can need two calls to find that two values are equal. A key function computes each key once, which helps when the key is expensive, such as a lower-case copy of a string.
History
J2SE 1.2, released in December 1998,12 added Comparable and Comparator to Java as part of the Collections Framework, and Comparable is marked "Since: 1.2".1 The documentation named the order of a class its natural ordering. Python 2.1 added the rich comparison methods with PEP 207, by Guido van Rossum and David Ascher.13 C++20 added the three-way comparison operator <=>, which a class can default, and Rust's derive generates PartialOrd and Ord from the fields.
References
- Comparable (Java SE 21 & JDK 21), API documentation, Interface Comparable
- cmp package, Go standard library, func Compare
- Data model, The Python Language Reference, 3.3.1 Basic customization, rich comparison methods
- functools, Python standard library, total_ordering; cmp_to_key
- Ord trait, Rust standard library, Description; Derivable
- Total order, Wikipedia, Introduction
- Comparator (Java SE 21 & JDK 21), API documentation, Interface Comparator
- IComparable<T> Interface, .NET API reference, Remarks
- Default comparisons, cppreference.com, Three-way comparison; Comparison category types
- Array.prototype.sort(), JavaScript reference, MDN, Description
- PartialOrd trait, Rust standard library, Strict and non-strict partial orders
- Java version history, Wikipedia, J2SE 1.2
- PEP 207, Rich Comparisons, Header
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 RF4SM8 Edit this page History Report an error Markdown