skip to content

In Rust, when do you pick `sort` over `sort_unstable` for a `Vec<T>`, and why does `values.sort()` on a `Vec<f32>` fail with E0277?

level: seniorimportance: should knowfreq 42%

answer

  1. equal elements keep their order
  2. auxiliary buffer vs in place
  3. Ord requires a total order
  4. NaN breaks reflexivity
  5. inconsistent Ord may panic since 1.81

basics

~20 s

sort is stable and may allocate a scratch buffer; sort_unstable may reorder equal elements but sorts in place without allocating. Both need T: Ord, which f32 lacks because NaN breaks total order, so float vectors use sort_by(f32::total_cmp).

solid answer

~40 s

Use `sort` (and `sort_by`, `sort_by_key`) when equal elements must keep their existing order, for example re-sorting readings by sensor while preserving arrival order; it is driftsort, O(n log n) worst case, and allocates an auxiliary buffer for all but short slices (up to `len`, clamped to `len / 2` for large ones). Otherwise prefer `sort_unstable`: ipnsort, in place, no allocation, usually faster. Both require `T: Ord`, and `f32` only implements `PartialOrd` because `NaN != NaN`, so `values.sort()` fails with E0277: the trait bound `f32: Ord` is not satisfied. Sort floats with `sort_unstable_by(f32::total_cmp)`, or `partial_cmp(..).unwrap()` when NaN is impossible. Since Rust 1.81 an `Ord` that is not a total order may make either sort panic.

code

rust · 23 lines
rust
#[derive(Debug)]
struct Reading { sensor: &'static str, ts: u64, value: f32 }

fn main() {
    // Already in arrival order
    let mut batch = vec![
        Reading { sensor: "b", ts: 10, value: 0.9 },
        Reading { sensor: "a", ts: 12, value: 0.1 },
        Reading { sensor: "b", ts: 11, value: 0.4 },
        Reading { sensor: "a", ts: 9, value: 0.7 },
    ];

    // Stable: within each sensor, arrival order survives
    batch.sort_by_key(|r| r.sensor);
    let order: Vec<u64> = batch.iter().map(|r| r.ts).collect();
    println!("{order:?}"); // [12, 9, 10, 11]

    // f32 is not Ord, so plain sort() does not compile; total_cmp gives a total order
    let mut values: Vec<f32> = batch.iter().map(|r| r.value).collect();
    values.push(f32::NAN);
    values.sort_unstable_by(f32::total_cmp);
    println!("{values:?}"); // NaN sorts last
}

go deeper

for a junior

Know that sort keeps equal elements in their original order, sort_unstable may not, and that a Vec of floats cannot call sort directly.

for a middle

Explain that both need Ord, why f32 has only PartialOrd, and how sort_by with f32::total_cmp or partial_cmp with unwrap fixes it.

for a senior

Discuss memory and failure modes: sort allocates a scratch buffer, sort_unstable does not and works in no_std, and since Rust 1.81 a broken comparator may panic rather than silently misorder.

for a principal

Set the team default to sort_unstable with an explicit comment wherever stability is relied on, and ban NaN-to-Equal float comparators in review.

## Two sorts on every slice `Vec<T>` dereferences to `[T]`, so its sorting methods are slice methods. They come in two families: - **Stable**: `sort`, `sort_by`, `sort_by_key`, `sort_by_cached_key`. "Stable" means **equal elements keep their original relative order**. - **Unstable**: `sort_unstable`, `sort_unstable_by`, `sort_unstable_by_key`. Equal elements may end up in any order. Both families are O(n log n) in the worst case. The differences are stability, memory and speed. | | `sort` family | `sort_unstable` family | |---|---|---| | Equal elements | keep their order | may be reordered | | Algorithm (rustc 1.99.1) | driftsort | ipnsort | | Extra memory | none for short slices, `len` for medium, clamped at `len / 2` beyond | none: in place | | Lives in | `alloc` (needs an allocator) | `core` (works in `no_std`) | | Typical speed | slower, except on partially sorted input | usually faster | The standard library's own advice is that unstable sorting "is preferred because it is generally faster than stable sorting and it doesn't allocate auxiliary memory", with partially sorted slices as the exception that may favour `sort`. ## When stability matters Stability matters whenever the existing order carries information: 1. **Multi-key ordering by successive sorts**: sort by time, then stably by sensor, and each sensor's readings stay in time order. 2. **Arrival order as a tie-break**: a batch already in arrival order, sorted by priority, keeps first-come-first-served within a priority. 3. **Deterministic output**: a report sorted by a key with many ties shows ties in input order instead of an order that depends on the algorithm. When the key is unique, or ties are truly interchangeable, stability buys nothing and `sort_unstable` is the better default. ## Why `Vec<f32>` will not `sort()` All the plain sorts require `T: Ord`, a **total order**: every pair compares, and comparison is reflexive, antisymmetric and transitive. `f32` and `f64` implement only `PartialOrd`, because IEEE 754 says `NaN` is not equal to itself and is unordered against every number. So: ```rust let mut values = vec![0.9_f32, 0.1, 0.4]; values.sort(); // error[E0277]: the trait bound `f32: Ord` is not satisfied ``` The fixes the documentation itself gives: - `values.sort_by(f32::total_cmp)` or `sort_unstable_by(f32::total_cmp)`: `total_cmp` defines a total order over every bit pattern, placing negative quiet NaN first and positive quiet NaN last, and distinguishing `-0.0` from `+0.0`. - `values.sort_by(|a, b| a.partial_cmp(b).unwrap())` when the values are guaranteed to contain no NaN; a NaN then panics at the `unwrap`. - A newtype key that implements `Ord` via `total_cmp`, when floats are sorted in many places. ## A broken Ord is now loud An `Ord` implementation or comparator that is not a total order, such as one that is not transitive or a hand-written float comparison that returns `Equal` for NaN against everything, violates the trait's contract. Rust 1.81 replaced both sort implementations with driftsort and ipnsort, and its release notes warn that the new sorts **may panic** on such input, where the old ones silently returned unsorted data. The docs promise only that the order is unspecified or the call may panic; either way the slice still holds all its original elements, so no memory safety is lost. Code that "worked" before 1.81 with a sloppy comparator can therefore start panicking after a toolchain upgrade, which is a production incident worth recognising. ## Reading the diagnostic The E0277 message for `values.sort()` names the missing bound directly, "the trait `Ord` is not implemented for `f32`", and lists integer types that do implement it. The fix is never to implement `Ord` for `f32` yourself: the orphan rule forbids implementing a foreign trait for a foreign type, and a comparison that hides NaN would break the very contract the sort relies on. Choose a comparator or a key type instead. ## Choosing in practice - Default to `sort_unstable` for numbers, IDs and other keys where ties are identical. - Use `sort_by_key` or `sort` when ties must keep input order, and say so in a comment. - Use `sort_by_cached_key` when computing the key is expensive, since it calls the key function at most once per element. - In `no_std` code without `alloc`, only the unstable family is available. - For floats, reach for `total_cmp`; never write a comparator that maps NaN to `Ordering::Equal`. - Equality with `PartialEq` and the rules for writing `Ord` by hand belong with the comparison traits; the point here is what the sort methods demand and promise.

  • Why might a Rust service that sorted with a hand-written comparator start panicking after a toolchain upgrade past 1.81?
    Rust 1.81 switched `sort` to driftsort and `sort_unstable` to ipnsort, which have a good chance of detecting a comparator that is not a total order and panicking, where the old implementations returned unsorted data silently. A comparator that is not transitive, or one mapping NaN to `Equal`, now surfaces as a panic; fix the comparator, for example with `total_cmp`.
  • In Rust, why can `no_std` code without `alloc` call `sort_unstable` but not `sort`?
    `sort_unstable` is defined in `core` and sorts in place without allocating. The stable `sort` lives in `alloc` because it may allocate an auxiliary buffer, so it is unavailable when no allocator exists.

  • sort_unstable can return elements out of order
  • sort never allocates because it sorts in place
  • f32 implements Ord, so values.sort() just works
  • Mapping NaN to Ordering::Equal is a safe float comparator
  • An inconsistent Ord can cause undefined behaviour in sort

Assumes Rust 1.99 on edition 2024; the driftsort and ipnsort implementations arrived in Rust 1.81, which made sorting with an inconsistent Ord or comparator liable to panic instead of silently returning unsorted data.