A comparator must define a consistent ordering

← Back to Blog & Articles

A sorting routine depends on a comparison rule that behaves consistently across all input records. A rule that contradicts itself can make results unpredictable even when the sorting algorithm is otherwise correct.

Worked example

Ordering names by length and then alphabetically gives a clear tie rule. If two names have different lengths, compare lengths. Otherwise compare the names. This produces a consistent sequence of comparisons. By contrast, a cyclic preference such as A before B, B before C, and C before A cannot describe a single sorted order.

What to check

Test repeated keys, negative numbers, and boundary values. For numeric keys, returning a subtraction as a comparison result can overflow in fixed-width integer languages. Use a comparison operation that avoids that arithmetic assumption. When values can be missing or contain floating-point NaN, define their placement deliberately. A documented ordering contract helps callers understand what the sorted result means.

Continue with the book

Explore the full treatment, worked examples, and exercises in Algorithms Made Simple.


Companion article for Algorithms Made Simple, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.

Scroll to Top