Sorting
slice::sort is a stable, O(n log n) sort. sort_unstable is usually faster and may reorder equal elements. Both need T: Ord, or you pass a comparison with sort_by.
Detailed Explanation
v.sort() sorts a &mut [T] in place when T: Ord. It is stable: equal elements keep their original order. The current standard library uses a modified Timsort / driftsort-style algorithm — O(n log n) worst case, faster on already-sorted runs. v.sort_unstable() uses a pattern-defeating quicksort (pdqsort) and does not promise to keep equal elements in order. It is often faster and uses less memory. Prefer sort_unstable when you do not need stability.
T: Ord is a total order. i32 has one. f64 does not, because NaN is not equal to itself, so Vec<f64> has no .sort(). You write v.sort_by(|a, b| a.partial_cmp(b).unwrap()) if you have proved there is no NaN, or v.sort_by(|a, b| a.total_cmp(b)) for IEEE total ordering. sort_by_key takes a key extractor: people.sort_by_key(|p| p.age). The key is computed per comparison unless you use sort_by_cached_key, which computes each key once and is the right choice when the key is expensive.
Sorting a Vec is in place and O(1) extra space for sort_unstable (plus log n stack). Stable sort may allocate a temporary buffer. Sorting a linked list is a different problem; collect to a Vec, sort, rebuild if you must.
BinaryHeap and BTreeMap keep order incrementally. If you need a sorted view after every insert, those structures beat "push then sort the whole vector" for mixed workloads. If you insert a batch and then sort once, a Vec plus sort is simpler and often faster.
When you call sort_unstable: default for numbers and ids. When you call sort: you need stability (sort by last name, then by first name in two passes). When you cannot implement Ord: sort_by.
Code Examples
fn main() {
let mut ids = vec![3, 1, 2, 1];
ids.sort_unstable();
println!("{ids:?}"); // prints: [1, 1, 2, 3]
let mut names = ["ada", "al", "grace"];
names.sort_by_key(|s| s.len());
println!("{names:?}"); // prints: ["al", "ada", "grace"]
}Common Gotchas
`f64` has no `Ord`
`v.sort()` will not compile. Use `total_cmp` or strip `NaN` first.
`sort_by_key` recomputes the key
An expensive key belongs in `sort_by_cached_key`, which allocates a parallel array of keys.
Stability needs two-pass sorts
Sort by the secondary key first, then stably by the primary key. `sort_unstable` breaks that.
Sorting `&mut [T]` requires exclusive access
You cannot hold an iterator over `v` while you sort `v`. Collect indices if you need both.