Sorting Vectors
Sort a Vector of Integers
This example sorts a Vector of integers via vec::sort. Alternative would
be to use 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]); }
Sort a Vector of Floats
A Vector of f32 or f64 can be sorted with vec::sort_by and 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]); }
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 Eq,
PartialEq, Ord and PartialOrd. These traits can be simply derived.
You can also provide a custom comparator function using a 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), ]); // 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), ]); }