Programming Search⌘K

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's compareTo, C#'s CompareTo, Go's cmp.Compare and C++'s operator<=> use this form. Go's Compare "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_ordering writes 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

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CAbsentC has no methods; qsort and bsearch take a comparison function that returns a negative number, zero or a positive number.
C#Native
JavaScriptAbsent
TypeScriptAbsentAs JavaScript; objects have no natural order, and sort needs a comparison function; no example file because it would repeat the JavaScript answer.
GoIdiom
RustStandard library
KotlinNativeA 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.
SQLDoes not applyORDER BY orders rows by column values; rows have no user methods.
BashDoes not applyBash has no user types; sort and the [[ < ]] test compare strings.
PowerShellNativePowerShell objects are .NET objects, and a type can implement IComparable; no example file because it would repeat the C# answer.
HTMLDoes not applyHTML has no values to order.
CSSDoes not applyCSS has no values to order.
Regular expressionsDoes not applyRegular 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. Comparator is "A comparison function, which imposes a total ordering on some collection of objects."7 In C#, CompareTo returns 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. PartialOrd allows values that cannot be compared, and Ord is the "Trait for types that form a total order."5 Floats are only PartialOrd, so Vec<f64>::sort does 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 a Compare method, which code passes to slices.SortFunc.
PythonGitHub
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)
Output
[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, and sorted and list.sort use <.
  • functools.total_ordering writes the other three methods from __eq__ and __lt__. Comparing tuples of the fields gives a lexicographic order with no extra code.
  • A key function gives a different order without a change to the class. When both methods return NotImplemented, Python raises TypeError, so a Version and 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';
}
Output
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 defaulted operator==, so == works with no more code.
  • The result type tells the strength of the order: int members give std::strong_ordering, and double gives std::partial_ordering, where a NaN compares as unordered.
JavaGitHub
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);
    }
}
Output
[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, and list.sort(null), Collections.sort, TreeSet and TreeMap use it.
  • compareTo compares the fields in order of importance with Integer.compare, which avoids the overflow of a - b.
  • A Comparator gives 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}";
}
Output
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, and List<T>.Sort, Array.Sort and SortedSet<T> use it.
  • CompareTo returns less than zero, zero or more than zero. By convention, any object is greater than null, so CompareTo(null) returns a positive number.
  • A Comparison<T> delegate or an IComparer<T> gives another order, here the minor number from largest to smallest.
JavaScriptGitHub
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(" "));
Output
[ 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, sort converts the items to strings and compares those, so 10 comes before 2.
  • The usual idiom is a static compare(a, b) that returns a negative number, zero or a positive number, passed to sort. 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)
}
Output
[{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 a Compare method, which slices.SortFunc takes as a function.
  • cmp.Or returns its first argument that is not zero, so it chains the comparisons of the fields.
  • cmp.Compare and slices.Sort treat NaN as less than any other number and equal to itself, which gives floats a total order; the operator < still gives false for NaN.
RustGitHub
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());
}
Output
0.9 1.2 1.10
None Some(Less)
[-1.0, 2.0, NaN] Greater
  • Verdict: stdlib. Ord is the trait of a total order and PartialOrd the trait of a partial order. #[derive(PartialOrd, Ord)] compares the fields in the order of their declaration.
  • Vec::sort needs Ord. f64 implements only PartialOrd: partial_cmp returns None for NaN, so a vector of floats needs sort_by with total_cmp.
  • Ordering is an enum with Less, Equal and Greater, and methods such as reverse and then combine comparisons.
  • 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 for f64::NAN, a <= a is 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, and functools.cmp_to_key turns 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 when a equals b, a sorted set and a hash set hold the same items.

Pitfalls

  • An order that is not consistent with equals. Java's BigDecimal is 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)", but equals does 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());
    }
}
Output
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. Use Integer.compare, cmp.Compare or <=>.
  • 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.
  • NaN in the data. With floats, NaN < x and NaN > x are both false, so a comparison built from < treats NaN as equal to every number. Use a total order for floats, such as Rust's total_cmp or Go's cmp.Compare, which considers NaN "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

  1. Comparable (Java SE 21 & JDK 21), API documentation, Interface Comparable
  2. cmp package, Go standard library, func Compare
  3. Data model, The Python Language Reference, 3.3.1 Basic customization, rich comparison methods
  4. functools, Python standard library, total_ordering; cmp_to_key
  5. Ord trait, Rust standard library, Description; Derivable
  6. Total order, Wikipedia, Introduction
  7. Comparator (Java SE 21 & JDK 21), API documentation, Interface Comparator
  8. IComparable<T> Interface, .NET API reference, Remarks
  9. Default comparisons, cppreference.com, Three-way comparison; Comparison category types
  10. Array.prototype.sort(), JavaScript reference, MDN, Description
  11. PartialOrd trait, Rust standard library, Strict and non-strict partial orders
  12. Java version history, Wikipedia, J2SE 1.2
  13. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/RF4SM8/text.yaml