Module 4Sorting & Custom ComparatorsLesson 13 of 2324 min
Custom Sorting: sort_by & sort_by_key
Sort pairs, strings by length, structs by field — interview gold.
sort_by_key
rust
v.sort_by_key(|s| s.len());
intervals.sort_by_key(|iv| iv[0]); // by startsort_by with cmp
rust
v.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));f64 caution
rust
v.sort_by(|a, b| a.partial_cmp(b).unwrap());Multi-key
Sort by score desc, then name asc:
rust
people.sort_by(|a, b|
b.score.cmp(&a.score).then_with(|| a.name.cmp(&b.name))
);Common interview sorts
- Intervals by start
- Tasks by deadline
- Frequency sort (count map then sort keys)
Challenge
Sort intervals [[1,3],[2,6],[8,10],[1,2]] by start then end.
Tips
- then / then_with chain keys
- partial_cmp for floats
- sort_by_key is readable
Try it live
Custom Sorting: sort_by & sort_by_keyRust 2021
Loading editor…
Output
Press Run to compile and execute.