Custom Comparators

Sorting by custom criteria.

Custom comparators let you sort by any criteria. A comparator takes two elements and returns whether the first should come before the second.

C++ example: Sort by absolute value.

sort(arr.begin(), arr.end(), [](int a, int b) {
    return abs(a) < abs(b);
});

Python example: Sort by second element of tuples.

arr.sort(key=lambda x: x[1])

Common patterns:

  • Sort strings by length: key=len in Python.
  • Sort by multiple keys: return a tuple as the key.
  • Reverse order: negate the key or use reverse=True.

Custom comparators must define a consistent ordering. If a<ba < b and b<cb < c, then a<ca < c (transitivity).