Fundamentals/Built-in Sort with Custom Comparator
← PrevNext →
Most languages provide a built-in sort that accepts an optional custom comparator: a two-argument function whose return value determines the relative order of two elements. By convention, a negative result places the first argument before the second, a positive result places the second before the first, and zero leaves their order unchanged.
A well-formed comparator must be transitive (if a precedes b and b precedes c, then a precedes c) and antisymmetric (if a precedes b, then b does not precede a). Violating either property yields an undefined ordering.
Using this contract, you can sort records by any chosen field in ascending order, flip the sign for descending order, or chain comparisons for multi-key sorts.