how to make a sorting algorithim rust
Sorting Algorithm in Rust
To implement a sorting algorithm in Rust, you can use the built-in sort
method provided by the Vec
type. The sort
method sorts the elements of a vector in ascending order based on their natural order. Here's an example:
fn main() {
let mut numbers = vec![5, 2, 8, 1, 9];
numbers.sort();
println!("{:?}", numbers);
}
In this example, we create a vector numbers
with some unsorted integers. We then call the sort
method on the vector, which sorts the elements in ascending order. Finally, we print the sorted vector using println!
.
The output of this code will be [1, 2, 5, 8, 9]
, which is the sorted version of the original vector.
If you want to sort the elements in descending order, you can use the sort_by
method and provide 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);
}
In this example, we use the sort_by
method and provide a closure that compares two elements in reverse order using the cmp
method. This sorts the elements in descending order.
The output of this code will be [9, 8, 5, 2, 1]
, which is the sorted version of the original vector in descending order.
These examples demonstrate how to use the built-in sorting methods in Rust to sort elements in ascending or descending order. You can apply these methods to any type that implements the Ord
trait, which includes most of the built-in types in Rust.