Searching
Binary Search (Iterative)
On a sorted array, narrow [lo, hi] window by halving until arr[mid]
equals the target or the window is empty. Demonstrates the
"discard half the search space" invariant.
Algorithm
Canonical input arr = [1, 3, 5, 7, 9, 11, 13] with target = 11
finishes in two frames: descend right to mid = 5, match.
Basic Implementation
basic.rs
fn main() {
let arr = [1, 3, 5, 7, 9, 11, 13];
let target = 11;
let mut lo: i32 = 0;
let mut hi: i32 = (arr.len() as i32) - 1;
let mut result: i32 = -1;
while lo <= hi {
let mid = lo + (hi - lo) / 2;
if arr[mid as usize] == target {
result = mid;
break;
}
if arr[mid as usize] < target {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
println!("{}", result);
}
Complexity
- Time: O(log n)
- Space: O(1)
Implementation notes
- Rust: compute
let mid = lo + (hi - lo) / 2;, not(lo + hi) / 2. Keeps the lesson aligned with overflow-safe practice even on small inputs. - The standard
slice::binary_searchwould hide the window-halving loop; the lesson is teaching the loop directly.loandhiare kept asi32so the-1initialisation ofresultis honest withoutOption<usize>. - The replay highlights the
[lo, hi]window, marksmid, and labels the branch taken (left half / right half / match).
midpoint
`mid = lo + (hi - lo) / 2` (overflow-safe integer division).
inclusive window
`hi` is inclusive. The loop runs while `lo <= hi`.