Rs
Module 4Sorting & Custom ComparatorsLesson 12 of 2320 min

sort, reverse, binary_search

In-place sort on Vec; reverse; binary_search API.

sort

rust
fn main() {
    let mut v = vec![3, 1, 4, 1, 5];
    v.sort(); // ascending for Ord types
    println!("sorted={v:?}");
    v.reverse();
    println!("reversed={v:?}");
}
Output
sorted=[1, 1, 3, 4, 5]
reversed=[5, 4, 3, 1, 1]

sort_unstable

Often faster; order of equal elements not preserved.

binary_search

rust
fn main() {
    let mut v = vec![3, 1, 4, 1, 5];
    v.sort(); // [1, 1, 3, 4, 5]
    match v.binary_search(&4) {
        Ok(i) => println!("found at {i}"),
        Err(i) => println!("insert at {i}"),
    }
}
Output
found at 3

Must be sorted first. Err gives insertion point — useful for LIS/patience patterns.

Challenge

Sort descending with sort_by(|a,b| b.cmp(a)).

Tips
  • sort needs Ord
  • binary_search needs sorted
  • Err is insert point

Try it live

sort, reverse, binary_searchRust 2021
Loading editor…
Output
Press Run to compile and execute.