Searching
Binary Search (Recursive)
Use the same binary-search window as the iterative lesson, but pass lo and hi through recursive calls.
Algorithm
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.
Basic Implementation
basic.rs
Replay: real traced execution (multi-file project)
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));
}
lo ← 0, hi ← 6, target ← 11
1fn search(arr: &[i32], target: i32, lo: i32, hi: i32) -> i32 {2 if lo > hi {values this step0lo6hi11targetmid ← 3, arr[mid] ← 7, next call ← (4, 6)
4}5let mid = lo + (hi - lo) / 2;6if arr[mid as usize] == target {values this step3mid7arr[mid](4, 6)next call0lo6himid ← 5, arr[mid] ← 11, result ← 5
4}5let mid = lo + (hi - lo) / 2;6if arr[mid as usize] == target {values this step5mid11arr[mid]5result4lo6histdout ← 5
17 let target = 11;18 println!("{}", search(&arr, target, 0, (arr.len() as i32) - 1));19}values this step5stdout5result
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.