Sorting By Functions in Rust

Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Rust.

use std::cmp::Ordering;

fn main() {
    let mut fruits = vec!["peach", "banana", "kiwi"];

    // We implement a comparison function for string lengths.
    let len_cmp = |a: &str, b: &str| a.len().cmp(&b.len());

    // Now we can call sort_by with this custom comparison function
    // to sort `fruits` by name length.
    fruits.sort_by(len_cmp);
    println!("{:?}", fruits);

    // We can use the same technique to sort a vector of
    // values that aren't built-in types.
    struct Person {
        name: String,
        age: u32,
    }

    let mut people = vec![
        Person { name: "Jax".to_string(), age: 37 },
        Person { name: "TJ".to_string(), age: 25 },
        Person { name: "Alex".to_string(), age: 72 },
    ];

    // Sort `people` by age using sort_by.
    //
    // Note: if the `Person` struct is large,
    // you may want the vector to contain `&Person` instead
    // and adjust the sorting function accordingly. If in
    // doubt, benchmark!
    people.sort_by(|a, b| a.age.cmp(&b.age));
    println!("{:?}", people.iter().map(|p| (&p.name, p.age)).collect::<Vec<_>>());
}

To run the program:

$ cargo run
["kiwi", "peach", "banana"]
[("TJ", 25), ("Jax", 37), ("Alex", 72)]

In this Rust example, we use the sort_by method on vectors to perform custom sorting. The sort_by method takes a closure that defines the comparison logic. For the fruits vector, we sort by string length, and for the people vector, we sort by age.

Rust’s standard library provides powerful and flexible sorting capabilities, allowing you to easily implement custom sorting logic for various data types.