Sorting Collections
In this page:
vec.sort();
vec.sort_by(|a, b| a.cmp(b));
vec.sort_by_key(|item| item.field);
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
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `numbers`, initialized to `vec![5, 1, 4, 2, 3]`
let mut numbers = vec![5, 1, 4, 2, 3];
numbers.sort();
// Print "{:?}" to the console, substituting in `numbers` (with a trailing newline)
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
// Define a struct `Person` to group related fields together
struct Person {
name: String,
age: u32,
}
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `people`, initialized to `vec![`
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);
// Loop over `&people`, binding each item to `p`
for p in &people {
// Print "{}: {}" to the console, substituting in `p.name, p.age` (with a trailing newline)
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
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `numbers`, initialized to `vec![3, 1, 4, 1, 5]`
let mut numbers = vec![3, 1, 4, 1, 5];
numbers.sort_by(|a, b| b.cmp(a));
// Print "{:?}" to the console, substituting in `numbers` (with a trailing newline)
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
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `prices`, initialized to `vec![9.99, 1.50, 5.25]`
let mut prices = vec![9.99, 1.50, 5.25];
prices.sort_by(|a, b| a.partial_cmp(b).unwrap());
// Print "{:?}" to the console, substituting in `prices` (with a trailing newline)
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: