Sorting Collections
In this page:
Basic Sorting
.sort() sorts a mutable Vec's elements in place, in ascending order, as long as the element type implements the Ord trait, which most built-in types do.
Example: Basic Sorting
fn main() {
let mut numbers = vec![5, 1, 4, 2, 3];
numbers.sort();
println!("{:?}", numbers);
}
Login to try C/C++/Java/PHP code in the editor
Sorting by a Key
.sort_by_key(|item| key) sorts elements based on a value derived from each one, which is convenient when sorting structs by one particular field.
Example: Sorting by a Key
struct Person {
name: String,
age: u32,
}
fn main() {
let mut people = vec![
Person { name: String::from("Bob"), age: 25 },
Person { name: String::from("Ann"), age: 30 },
];
people.sort_by_key(|p| p.age);
for p in &people {
println!("{}: {}", p.name, p.age);
}
}
Login to try C/C++/Java/PHP code in the editor
Custom Comparisons with sort_by
.sort_by(|a, b| ...) gives full control over ordering by providing your own comparator function, useful for descending order or types without a natural ordering.
Example: Custom Comparisons with sort_by
fn main() {
let mut numbers = vec![3, 1, 4, 1, 5];
numbers.sort_by(|a, b| b.cmp(a));
println!("{:?}", numbers);
}
Login to try C/C++/Java/PHP code in the editor
Sorting Floating-Point Numbers
Floating-point numbers don't implement Ord because NaN cannot be meaningfully compared, so sorting them uses partial_cmp inside .sort_by() instead of the plain .sort().
Example: Sorting Floating-Point Numbers
fn main() {
let mut prices = vec![9.99, 1.50, 5.25];
prices.sort_by(|a, b| a.partial_cmp(b).unwrap());
println!("{:?}", prices);
}
Login to try C/C++/Java/PHP code in the editor
- Calling
.sort()on aVecof floats, which fails to compile since floats don't implementOrd--.sort_by()withpartial_cmpis needed instead. - Forgetting
.sort()requires theVecbinding to be mutable, since it sorts the elements in place. - Using
.sort()when a stable custom order is needed, instead of.sort_by_key()or.sort_by()for more control.
.sort()sorts aVecin place in ascending order, requiring elements to implementOrd..sort_by_key(|x| ...)sorts based on a derived key rather than the elements' natural order..sort_by(|a, b| ...)gives full custom control over the comparison, useful for descending order or floats.- Rust's sort is stable, meaning equal elements keep their original relative order.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: