Searching
Binary Search (Recursive)
Use the same binary-search window as the iterative lesson, but pass lo and hi through recursive calls.
Algorithm
Basic Implementation
basic.rs
fn search(arr: &[i32], target: i32, lo: i32, hi: i32) -> i32 {
if lo > hi {
return -1;
}
let mid = lo + (hi - lo) / 2;
if arr[mid as usize] == target {
return mid;
}
if arr[mid as usize] < target {
return search(arr, target, mid + 1, hi);
}
search(arr, target, lo, mid - 1)
}
fn main() {
let arr = [1, 3, 5, 7, 9, 11, 13];
let target = 11;
println!("{}", search(&arr, target, 0, (arr.len() as i32) - 1));
}
Complexity
- Time: O(log n)
- Space: O(log n) call stack
Implementation notes
mainuses a fixed sorted array,let arr = [1, 3, 5, 7, 9, 11, 13], and passes it as&arrto the recursive function.- The signature is
fn search(arr: &[i32], target: i32, lo: i32, hi: i32) -> i32. The slice is borrowed read-only, while the search bounds are signed integers. - The base case
if lo > hi { return -1; }uses-1as the not-found sentinel; this checked source does not returnOption. midis computed aslo + (hi - lo) / 2, then cast withmid as usizeforarr[mid as usize]. The base case keeps negative bounds from being indexed.- Branch order checks equality first and returns
midon a hit. Ifarr[mid] < target, the right call issearch(arr, target, mid + 1, hi); otherwise the left call issearch(arr, target, lo, mid - 1). - Signed bounds avoid
usizeunderflow when formingmid - 1; recursive stack frames carry the borrowed slice, target, and currentlo/hi. - The trace records the initial call
(0, 6), thenmid=3with value7and next call(4, 6). In that framemid=5matches11and returns5. println!("{}", search(...))uses display formatting and prints5.
execution replay
The checked-in replay follows the language-neutral state table for `search-binary-recursive`.
cross-language comparison
This Rust DSA version keeps the same data and final output as every other DSA book in this wave.