Skip to content

slice::sort_unstable

slice methods · Collections

Level: reference · for working programmers

One line: Sort in place, ascending, without promising that equal elements keep their order — and without allocating.

pub fn sort_unstable(&mut self)
where
    T: Ord,

Stable since 1.20.0.

Unstable is about equal elements, not about correctness: the result is sorted either way, but two elements that compare equal may come out in either order. In exchange it sorts in place with no temporary buffer and is typically faster than sort.

When equality is total — integers, or strings compared whole — the two sorts are indistinguishable, and this is the one to reach for. The difference only shows when the comparison ignores part of the element: sorting records by one field, where the other fields distinguish "equal" records. The program does exactly that, with sort_by_key against sort_unstable_by_key. On six elements the unstable sort happened to keep the ties in order; nothing promises it.

Same Ord bound, same E0277 on floats, same () return as sort.

Example

slice_sort_unstable.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let mut nums = vec![5, 3, 9, 1, 3];
    nums.sort_unstable();
    println!("{nums:?}");

    // "Unstable" is about the relative order of EQUAL elements. Sort by the
    // first field only, so the letters show whether the ties moved.
    let mut stable = vec![(1, "a"), (0, "b"), (1, "c"), (0, "d"), (1, "e"), (0, "f")];
    let mut unstable = stable.clone();
    stable.sort_by_key(|p| p.0);
    unstable.sort_unstable_by_key(|p| p.0);
    println!("stable:   {stable:?}");
    println!("unstable: {unstable:?}");
    println!("same order on this input: {}", stable == unstable);

    // With a total comparison there is nothing to distinguish, so prefer this one.
    let mut words = vec!["pear", "fig", "apple"];
    words.sort_unstable();
    println!("{words:?}");
}

Verified output of slice_sort_unstable.rs — regenerated by tools/run_examples.py, never hand-typed.

[1, 3, 3, 5, 9]
stable:   [(0, "b"), (0, "d"), (0, "f"), (1, "a"), (1, "c"), (1, "e")]
unstable: [(0, "b"), (0, "d"), (0, "f"), (1, "a"), (1, "c"), (1, "e")]
same order on this input: true
["apple", "fig", "pear"]

See also

slice::sort_unstable in the standard library ↗