To sort a vector in Rust, you can use the sort
method available for vectors. This method allows you to sort the elements of a vector in ascending order.
In this example,
vec
containing several numeric values.sort
method on the vector vec
. This method sorts the elements of the vector in ascending order in place.println!
macro.fn main() {
// Step 1: Create a vector
let mut vec = vec![5, 2, 8, 3, 9, 1];
// Step 2: Sort the vector in ascending order
vec.sort();
// Step 3: Print the sorted vector
println!("Sorted vector: {:?}", vec);
}
Sorted vector: [1, 2, 3, 5, 8, 9]
In this example,
vec
containing several numeric values.sort
method on the vector vec
, passing a closure that compares elements in descending order. This method sorts the elements of the vector in descending order in place.println!
macro.fn main() {
// Step 1: Create a 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 tutorial, we learned How to Sort a Vector in Rust language with well detailed examples.