Sorting in Rust

Rust’s standard library provides sorting functionality for slices of types that implement the Ord trait. Let’s look at sorting for built-in types first.

use std::cmp::Ord;

fn main() {
    // Sorting functions work for any type that implements the Ord trait.
    // This includes most built-in types like strings, integers, and floats.
    let mut strs = vec!["c", "a", "b"];
    strs.sort();
    println!("Strings: {:?}", strs);

    // An example of sorting integers.
    let mut ints = vec![7, 2, 4];
    ints.sort();
    println!("Ints:    {:?}", ints);

    // We can also use the is_sorted() method to check if a slice is already in sorted order.
    let s = ints.is_sorted();
    println!("Sorted:  {}", s);
}

To run the program:

$ cargo run
Strings: ["a", "b", "c"]
Ints:    [2, 4, 7]
Sorted:  true

In this Rust example, we use the sort() method available on vectors (which are backed by slices) to sort the elements in place. The sort() method uses the natural ordering of the elements, which is defined by the Ord trait.

For strings, the sorting is lexicographical, and for integers, it’s numerical. The is_sorted() method is used to check if a slice is already in sorted order.

Note that unlike Go, Rust’s sorting methods are implemented directly on the slice (or vector) type, rather than being in a separate package. This makes the API slightly different, but the functionality is essentially the same.