← 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.
Syntax
rust
vec.sort();
vec.sort_by(|a, b| a.cmp(b));
vec.sort_by_key(|item| item.field);

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
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `numbers`, initialized to `vec![5, 1, 4, 2, 3]`
    let mut numbers = vec![5, 1, 4, 2, 3];
    numbers.sort();
    // Print "{:?}" to the console, substituting in `numbers` (with a trailing newline)
    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
// Define a struct `Person` to group related fields together
struct Person {
    name: String,
    age: u32,
}

// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `people`, initialized to `vec![`
    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);
    // Loop over `&people`, binding each item to `p`
    for p in &people {
        // Print "{}: {}" to the console, substituting in `p.name, p.age` (with a trailing newline)
        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
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `numbers`, initialized to `vec![3, 1, 4, 1, 5]`
    let mut numbers = vec![3, 1, 4, 1, 5];
    numbers.sort_by(|a, b| b.cmp(a));
    // Print "{:?}" to the console, substituting in `numbers` (with a trailing newline)
    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
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `prices`, initialized to `vec![9.99, 1.50, 5.25]`
    let mut prices = vec![9.99, 1.50, 5.25];
    prices.sort_by(|a, b| a.partial_cmp(b).unwrap());
    // Print "{:?}" to the console, substituting in `prices` (with a trailing newline)
    println!("{:?}", prices);
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.