skip to content

In Rust, how do you sort a Vec<Player> by score descending, then name ascending, using Ordering::then_with, sort_by_key or Reverse?

level: middleimportance: should knowfreq 50%

answer

  1. swap the operands
  2. chain only on a tie
  3. a wrapper that flips one key
  4. keys must be owned

basics

~10 s

Use sort_by with b.score.cmp(&a.score).then_with(|| a.name.cmp(&b.name)), or sort_by_key returning (Reverse(p.score), p.name.clone()). Reverse flips one key; then_with runs the tie-breaker only when the first comparison is Equal.

solid answer

~30 s

`std::cmp::Ordering` has combinators for multi-key comparisons. `a.then(b)` returns `a` unless it is `Equal`, in which case it returns `b`; `then_with` takes a closure and only calls it on a tie, so the second comparison is skipped when the first decides. For score-descending-then-name, write `board.sort_by(|a, b| b.score.cmp(&a.score).then_with(|| a.name.cmp(&b.name)))`: swapping `a` and `b` reverses one key. With keys, `board.sort_by_key(|p| (Reverse(p.score), p.name.clone()))` works because tuples compare lexicographically and `Reverse` inverts one component, but the key must be owned, so the `String` is cloned on every comparison; `sort_by_cached_key` computes each key at most once. A borrowed key such as `|p| &p.name` does not compile.

code

rust · 30 lines
rust
use std::cmp::Reverse;

#[derive(Debug, Clone)]
struct Player { name: String, score: u32 }

fn names(v: &[Player]) -> Vec<&str> {
    v.iter().map(|p| p.name.as_str()).collect()
}

fn main() {
    let board = vec![
        Player { name: "zoe".into(), score: 90 },
        Player { name: "bob".into(), score: 120 },
        Player { name: "amy".into(), score: 90 },
    ];

    // Comparator: score high to low, ties by name A to Z. No allocation.
    let mut a = board.clone();
    a.sort_by(|x, y| y.score.cmp(&x.score).then_with(|| x.name.cmp(&y.name)));

    // Key: Reverse flips one component; the String clone is the price of a key.
    let mut b = board.clone();
    b.sort_by_key(|p| (Reverse(p.score), p.name.clone()));

    // Cached key: the key closure runs at most once per element.
    let mut c = board.clone();
    c.sort_by_cached_key(|p| (Reverse(p.score), p.name.clone()));

    println!("{:?}\n{:?}\n{:?}", names(&a), names(&b), names(&c));
}

go deeper

for a junior

Recall that sort_by takes a closure returning Ordering and that swapping a and b sorts descending.

for a middle

Explain then versus then_with, how tuple keys and Reverse compose, and why sort_by_key needs an owned key.

for a senior

Choose comparator, key or cached key by cost, and catch reverse-after-sort and Reverse-on-the-whole-tuple bugs in review.

for a principal

Prefer named comparator functions for business orderings so the rule lives in one place rather than in a derived Ord tied to field layout.

## The tools in std::cmp Every comparison in Rust ends in a `std::cmp::Ordering`: `Less`, `Equal` or `Greater`. Three small methods on it, plus one wrapper type, cover almost every custom sort: | Item | What it does | Since | |---|---|---| | `Ordering::then(other)` | returns `self` unless `self` is `Equal`, else `other` | 1.17 | | `Ordering::then_with(f)` | same, but `f` is called only when `self` is `Equal` | 1.17 | | `Ordering::reverse()` | swaps `Less` and `Greater` | 1.0 | | `std::cmp::Reverse<T>` | a wrapper whose `Ord` is `T`'s, reversed | 1.19 | All of these are long stable, so they need no special edition or release. ## Approach 1: a comparator with sort_by `slice::sort_by` takes a closure `FnMut(&T, &T) -> Ordering`. For a leaderboard of `Player { name: String, score: u32 }`: ```rust board.sort_by(|a, b| { b.score.cmp(&a.score) // descending: operands swapped .then_with(|| a.name.cmp(&b.name)) // ascending tie-breaker }); ``` - **Descending** comes from comparing `b` with `a` instead of `a` with `b`. `a.score.cmp(&b.score).reverse()` says the same thing more explicitly. - **`then_with`** only evaluates the name comparison when scores tie. `then` would take an already-computed `Ordering`, so the string comparison would run for every pair. For a cheap key the difference is small; for an expensive one, prefer `then_with`. - The comparator borrows both players, so nothing is cloned or allocated. ## Approach 2: a key with sort_by_key `slice::sort_by_key` takes `FnMut(&T) -> K` where `K: Ord`. Tuples implement `Ord` lexicographically, so a tuple key expresses "first this, then that", and `Reverse` flips one component: ```rust board.sort_by_key(|p| (Reverse(p.score), p.name.clone())); ``` Two things to know about keys: 1. **The key cannot borrow from the element.** `board.sort_by_key(|p| &p.name)` fails with `error: lifetime may not live long enough`: the key type `K` is a single type for the whole call and cannot carry the lifetime of each `&T` handed to the closure. Owned keys work, hence the `clone()`. 2. **The key function runs on each comparison.** For `sort_by_key` that means the `String` clone happens twice per comparison, many times per element. `sort_by_cached_key` calls the key function at most once per element and stores the results, which pays off when the key is expensive to build. ## Choosing between them - Use **`sort_by` with `then_with`** when keys are borrowed fields or descending on some keys; it allocates nothing and reads like the rule. - Use **`sort_by_key`** when the key is cheap and `Copy`, such as `|p| Reverse(p.score)` or `|p| (p.tier, p.score)`. - Use **`sort_by_cached_key`** when computing the key is expensive, for example normalising a name with `to_lowercase()`. - Use a **hand-written `Ord`** only when this ordering is the type's one natural order; a leaderboard rule is usually better as a comparator at the call site. Naming the comparator lets every call site share one definition. With `fn by_rank(a: &Player, b: &Player) -> Ordering` holding the rule: 1. `board.sort_by(by_rank)` passes the function directly, since `sort_by` hands it two `&Player`. 2. `board.iter().min_by(|a, b| by_rank(a, b))` finds the leader without sorting. Passing `by_rank` directly fails with E0631, because `min_by` on an iterator of `&Player` supplies `&&Player` arguments; the closure lets auto-deref bridge the gap. 3. `board.binary_search_by(|p| by_rank(p, &target))` must use the **same** comparator the sort used, or it searches an order the slice is not in. ## Pitfalls that show up in review 1. **Reversing the whole vector after an ascending sort.** `sort_by_key(|p| p.score)` followed by `reverse()` gives descending scores but also reverses whatever order tied players were in. Put the direction on the key, not on the result. 2. **Sorting by name, then by score, expecting both.** Because `sort_by` and `sort_by_key` are stable, sorting by name first and then by score does produce "score, then name", but it is two passes and easy to get backwards. One comparator says it once. 3. **Using `Reverse` on the whole tuple.** `Reverse((p.score, p.name.clone()))` reverses both components, giving names Z to A within a score. 4. **Floating-point scores.** `f64` is not `Ord`, so `Reverse(p.rating)` will not compile as a key; compare with `b.rating.total_cmp(&a.rating)` in a `sort_by` instead. The leaderboard rule, written once as a comparator, survives refactors of the `Player` struct that a derived ordering would not.

  • When does then instead of then_with actually cost you something?
    `then` takes an already-computed `Ordering`, so its argument is evaluated for every pair even when the first key already decided. With a cheap integer comparison the difference is noise; with a string comparison, a lookup or a lowercase conversion it is wasted work. `then_with` defers that work to ties only.
  • Why is sort_by_cached_key sometimes faster than sort_by_key, and when is it slower?
    `sort_by_cached_key` calls the key function at most once per element and sorts the stored keys, so an expensive key such as `to_lowercase()` is built n times instead of on every comparison. It needs extra memory for the cached keys, so for cheap `Copy` keys like an integer score, plain `sort_by_key` is usually faster.

  • Ordering::then_with always calls its closure, so it is just a slower then.
  • Wrapping the whole tuple key in Reverse reverses only the first component.
  • sort_by_key(|p| &p.name) is fine because the closure only borrows.
  • Sorting ascending and then calling reverse() keeps ties in name order.
  • std::cmp::Reverse negates the number before the comparison happens.