← Back to Rust Course | Chapter 9: Collections | Lesson 6 of 6

Sorting Collections

Sorting puts everything in a list into a neat, predictable order, like arranging books from shortest to tallest.

Basic Sorting

.sort() sorts a mutable Vec's elements in place, in ascending order, as long as the element type implements the Ord trait, which most built-in types do.

Example: Basic Sorting

markup
fn main() {
    let mut numbers = vec![5, 1, 4, 2, 3];
    numbers.sort();
    println!("{:?}", numbers);
}

Sorting by a Key

.sort_by_key(|item| key) sorts elements based on a value derived from each one, which is convenient when sorting structs by one particular field.

Example: Sorting by a Key

markup
struct Person {
    name: String,
    age: u32,
}

fn main() {
    let mut people = vec![
        Person { name: String::from("Bob"), age: 25 },
        Person { name: String::from("Ann"), age: 30 },
    ];
    people.sort_by_key(|p| p.age);
    for p in &people {
        println!("{}: {}", p.name, p.age);
    }
}

Custom Comparisons with sort_by

.sort_by(|a, b| ...) gives full control over ordering by providing your own comparator function, useful for descending order or types without a natural ordering.

Example: Custom Comparisons with sort_by

markup
fn main() {
    let mut numbers = vec![3, 1, 4, 1, 5];
    numbers.sort_by(|a, b| b.cmp(a));
    println!("{:?}", numbers);
}

Sorting Floating-Point Numbers

Floating-point numbers don't implement Ord because NaN cannot be meaningfully compared, so sorting them uses partial_cmp inside .sort_by() instead of the plain .sort().

Example: Sorting Floating-Point Numbers

markup
fn main() {
    let mut prices = vec![9.99, 1.50, 5.25];
    prices.sort_by(|a, b| a.partial_cmp(b).unwrap());
    println!("{:?}", prices);
}
Common Mistakes
  1. Calling .sort() on a Vec of floats, which fails to compile since floats don't implement Ord -- .sort_by() with partial_cmp is needed instead.
  2. Forgetting .sort() requires the Vec binding to be mutable, since it sorts the elements in place.
  3. Using .sort() when a stable custom order is needed, instead of .sort_by_key() or .sort_by() for more control.
Chapter Summary
  • .sort() sorts a Vec in place in ascending order, requiring elements to implement Ord.
  • .sort_by_key(|x| ...) sorts based on a derived key rather than the elements' natural order.
  • .sort_by(|a, b| ...) gives full custom control over the comparison, useful for descending order or floats.
  • Rust's sort is stable, meaning equal elements keep their original relative order.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.