To sort an array in descending order in Rust, you can use the `sort_by` method with a custom comparison function.
In this example,
numbers
.sort_by
method with the custom comparison function to sort the vector of integers in descending order.fn main() {
let mut numbers = vec![5, 2, 8, 1, 9];
numbers.sort_by(|a, b| b.cmp(a));
println!("Sorted array in descending order: {:?}", numbers);
}
Sorted array in descending order: [9, 8, 5, 2, 1]
In this example,
words
.sort_by
method with the custom comparison function to sort the vector of strings in descending order.fn main() {
let mut words = vec!["apple", "banana", "cherry", "date"];
words.sort_by(|a, b| b.cmp(a));
println!("Sorted array in descending order: {:?}", words);
}
Sorted array in descending order: [date, cherry, banana, apple]
In this tutorial, we learned How to Sort an Array in Descending Order in Rust language with well detailed examples.