typestar

Sorting and searching in Rust

Sorting by a comparator, finding extremes, and searching a sorted slice.

fn main() {
    let mut scores = vec![3.5, 1.25, 9.0, 4.75];
    scores.sort_by(|a, b| b.partial_cmp(a).unwrap());
    println!("{:?}", scores);

    let words = ["fig", "banana", "kiwi"];
    let longest = words.iter().max_by_key(|w| w.len());
    println!("{:?}", longest);

    let sorted = [1, 4, 9, 16, 25];
    println!("{:?}", sorted.binary_search(&9));
    println!("{:?}", sorted.binary_search(&10));
}

How it works

  1. sort_by takes a comparator; partial_cmp covers floats.
  2. max_by_key finds the largest by a derived value.
  3. binary_search needs the slice already sorted.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
375
Tokens
143
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 95 seconds.

Type this snippet

Step 3 of 8 in Collections, step 32 of 39 in Language basics.

← Previous Next →

Sorting and searching in other languages