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
sort_bytakes a comparator;partial_cmpcovers floats.max_by_keyfinds the largest by a derived value.binary_searchneeds the slice already sorted.
Keywords and builtins used here
fnletmainmut
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.
Step 3 of 8 in Collections, step 32 of 39 in Language basics.