Sorting Vectors
Recipe | Crates | Categories |
---|---|---|
Sort a vector of integers | ||
Sort a vector of floats | ||
Sort a vector of structs |
Sort a vector of integers
This example will sort a Vector of integers via std::vec::Vec::sort
⮳. Alternative would be to use std::vec::Vec::sort_unstable
⮳ which can be faster, but does not preserve the order of equal elements.
fn main() { let mut vec = vec![1, 5, 10, 2, 15]; vec.sort(); assert_eq!(vec, vec![1, 2, 5, 10, 15]); println!("{:?}", vec); }
Sort a vector of floats
A vector of f32 or f64 can be sorted with sort_by
and std::cmp::PartialOrd::partial_cmp
⮳.
fn main() { let mut vec = vec![1.1, 1.15, 5.5, 1.123, 2.0]; vec.sort_by(|a, b| a.partial_cmp(b).unwrap()); assert_eq!(vec, vec![1.1, 1.123, 1.15, 2.0, 5.5]); println!("{:?}", vec); }
Sort a vector of structs
Sorts a vector of Person structs with properties name
and age
by its natural order (by name and age). In order to make Person
sortable you need four traits std::cmp::Eq
⮳, std::cmp::PartialEq
⮳, std::cmp::Ord
⮳ and std::cmp::PartialOrd
⮳. These traits can be simply derived. You can also provide a custom comparator function using a std::vec::Vec::sort_by
⮳ method and sort only by age.
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] struct Person { name: String, age: u32, } impl Person { pub fn new(name: String, age: u32) -> Self { Person { name, age } } } fn main() { let mut people = vec![ Person::new("Zoe".to_string(), 25), Person::new("Al".to_string(), 60), Person::new("John".to_string(), 1), ]; // Sort people by derived natural order (Name and age) people.sort(); assert_eq!(people, vec![ Person::new("Al".to_string(), 60), Person::new("John".to_string(), 1), Person::new("Zoe".to_string(), 25), ]); println!("{:?}", people); // Sort people by age people.sort_by(|a, b| b.age.cmp(&a.age)); assert_eq!(people, vec![ Person::new("Al".to_string(), 60), Person::new("Zoe".to_string(), 25), Person::new("John".to_string(), 1), ]); println!("{:?}", people); }
See also
glidesort⮳ is a Rust implementation of Glidesort, a stable adaptive quicksort/mergesort hybrid sorting algorithm.