RRust By Example
intermediateCollections

Sorting Vectors

Sort vectors with sort, sort_by, and sort_unstable.

Sorting Vectors

Sort vectors with sort, sort_by, and sort_unstable.

Difficulty

Intermediate

Code

rust
fn main() {
    let mut nums = vec![5, 2, 8, 1, 9, 3];
    nums.sort();
    println!("sorted: {:?}", nums);

    let mut words = vec!["banana", "apple", "cherry"];
    words.sort_by(|a, b| a.len().cmp(&b.len()));
    println!("by length: {:?}", words);

    // custom struct sorting
    #[derive(Debug)]
    struct Student { name: String, grade: u32 }

    let mut students = vec![
        Student { name: "Alice".into(), grade: 90 },
        Student { name: "Bob".into(), grade: 85 },
        Student { name: "Charlie".into(), grade: 95 },
    ];
    students.sort_by(|a, b| b.grade.cmp(&a.grade));
    println!("by grade desc: {:?}", students);
}

Explanation

sort() sorts in place. sort_by takes a comparator.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the collections category to build a complete understanding of this topic.

More Collections Examples