To sort a vector in descending order in Rust, you can use the sort_by
method with a custom comparison function.
In this example,
vec
containing several numeric values.sort_by
method on the vector vec
, passing a custom comparison function that sorts elements in descending order. This method sorts the elements of the vector in descending order.println!
macro.fn main() {
// Step 1: Create a mutable vector
let mut vec = vec![5, 2, 8, 3, 9, 1];
// Step 2: Sort the vector in descending order
vec.sort_by(|a, b| b.cmp(a));
// Step 3: Print the sorted vector
println!("Sorted vector: {:?}", vec);
}
Sorted vector: [9, 8, 5, 3, 2, 1]
In this example,
vec
containing several string values.sort_by
method on the vector vec
, passing a custom comparison function that sorts elements in descending order based on lexicographic order. This method sorts the elements of the vector in descending order.println!
macro.fn main() {
// Step 1: Create a mutable vector
let mut vec = vec!["apple", "banana", "orange", "grape", "kiwi"];
// Step 2: Sort the vector in descending order
vec.sort_by(|a, b| b.cmp(a));
// Step 3: Print the sorted vector
println!("Sorted vector: {:?}", vec);
}
Sorted vector: ["orange", "kiwi", "grape", "banana", "apple"]
In this tutorial, we learned How to Sort a Vector in Descending Order in Rust language with well detailed examples.