sort an array in rust

In Rust, arrays can be sorted easily by calling the sort() method on the array slice. Here's an example:

main.rs
fn main() {
    let mut arr = [5, 2, 9, 7, 1];
    arr.sort();

    println!("{:?}", arr);
}
93 chars
7 lines

This will output:

main.rs
[1, 2, 5, 7, 9]
16 chars
2 lines

Note that we had to mark the array as mut in order to sort it in place. If you don't want to modify the original array, you can use the sorted() method instead:

main.rs
fn main() {
    let arr = [5, 2, 9, 7, 1];
    let sorted = arr.sorted();

    println!("{:?}", sorted);
}
107 chars
7 lines

This will output:

main.rs
[1, 2, 5, 7, 9]
16 chars
2 lines

Keep in mind that sorting large arrays can be a performance hit, so be sure to use the appropriate sorting algorithm for your use case.

gistlibby LogSnag