Search and sorting
Quick answer
Searching finds a matching item; sorting establishes an order. Rust slices already provide efficient implementations for common tasks.
Respect the sorted invariant
Linear search works on unsorted data in O(n) comparisons. Binary search needs data sorted with a consistent ordering and uses O(log n) comparisons. sort preserves the order of equal elements; sort_unstable need not. Sorting first may not be worthwhile for a single search.
fn main() { let values = [8, 3, 1]; println!("{:?}", values.iter().position(|&x| x == 3));}Expected stdout (not executed):
Some(1)The result is the index in the original order.
fn main() { let mut values = [8, 3, 1]; values.sort_unstable(); println!("{:?} {:?}", values.binary_search(&3), values.binary_search(&4));}Expected stdout (not executed):
Ok(1) Err(2)The missing-value error contains an insertion index.
Common mistake
Binary search on unsorted data has no meaningful result guarantee.
Try it yourself
Sort a list containing duplicates and check whether a chosen value is present without requiring a specific duplicate index.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Search and sorting — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
Records with equal keys must keep their input order. Which sorting method fits?
Search and sorting — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let values = [8, 3, 1]; println!("{:?}", values.iter().position(|&x| x == 3)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Search and sorting — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let mut values = [8, 3, 1]; values.sort_unstable(); println!("{:?} {:?}", values.binary_search(&3), values.binary_search(&4)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.