sort a vector rust
To sort a vector in Rust, you can use the sort
method provided by the Vec
type. Here's an example:
fn main() {
let mut numbers = vec![5, 2, 1, 4, 3];
numbers.sort();
println!("{:?}", numbers);
}
This code creates a mutable vector numbers
containing [5, 2, 1, 4, 3]
. Then, the sort
method is called on the vector, which sorts the elements in ascending order. Finally, the sorted vector is printed using println!
.
When you run this code, the output will be [1, 2, 3, 4, 5]
, as the vector has been sorted in ascending order.
If you want to sort the vector in descending order, you can use the sort_by
method instead, along with a custom comparison function. Here's an example:
fn main() {
let mut numbers = vec![5, 2, 1, 4, 3];
numbers.sort_by(|a, b| b.cmp(a));
println!("{:?}", numbers);
}
This code uses the sort_by
method with a closure that compares the elements in reverse order using the cmp
method. The output will be [5, 4, 3, 2, 1]
, as the vector has been sorted in descending order.
I hope this helps! Let me know if you have any further questions.