To sort an array in Rust, you can use the sort() method from the standard library.
In this example,
numbers
with values 5, 2, 8, 1, 6.sort()
method from the standard library to sort the array in ascending order.sort()
method sorts the array elements in ascending order.numbers
to the console.fn main() {
let mut numbers = [5, 2, 8, 1, 6];
numbers.sort();
println!("Sorted array in ascending order: {:?}", numbers);
}
Sorted array in ascending order: [1, 2, 5, 6, 8]
In this example,
numbers
with values 5, 2, 8, 1, 6.sort_by()
method with our custom closure to sort the array in descending order.numbers
to the console.fn main() {
let mut numbers = [5, 2, 8, 1, 6];
numbers.sort_by(|a, b| b.cmp(a));
println!("Sorted array in descending order: {:?}", numbers);
}
Sorted array in descending order: [8, 6, 5, 2, 1]
In this tutorial, we learned How to Sort an Array in Rust language with well detailed examples.