rust sort vector of number descending
To sort a vector of numbers in descending order in Rust, you can use the sort
method from the Vec
type, along with a custom comparison function. Here's an example:
fn main() {
let mut numbers = vec![5, 2, 8, 1, 9];
numbers.sort_by(|a, b| b.cmp(a));
println!("{:?}", numbers);
}
This will output [9, 8, 5, 2, 1]
, which is the vector sorted in descending order. The sort_by
method takes a closure that defines the comparison between elements. In this case, we use the cmp
method to compare the elements in reverse order (b.cmp(a)
).