What if you could find anything in a huge list by looking at just a few places?
Why Binary Search Recursive Approach in DSA Rust?
Imagine you have a thick book with thousands of pages, and you want to find a specific word. You start from the first page and flip through every page one by one until you find it.
This method is very slow and tiring because you check every page even if the word is near the end. It wastes time and effort, especially when the book is huge.
Binary search uses a smart trick: it looks at the middle page first, then decides if the word is in the first half or the second half. It repeats this process on smaller sections, quickly zeroing in on the word without checking every page.
fn linear_search(array: &[i32], target: i32) -> Option<usize> {
for (index, &value) in array.iter().enumerate() {
if value == target {
return Some(index);
}
}
None
}fn binary_search_recursive(array: &[i32], target: i32, left: usize, right: usize) -> Option<usize> {
if left > right {
return None;
}
let middle = left + (right - left) / 2;
if array[middle] == target {
Some(middle)
} else if array[middle] > target {
if middle == 0 {
return None;
}
binary_search_recursive(array, target, left, middle - 1)
} else {
binary_search_recursive(array, target, middle + 1, right)
}
}This approach lets you find items in sorted lists very fast, saving time and effort even with huge data.
When you search for a contact in your phone's sorted list, the phone uses a method like binary search to quickly find the name without scrolling through every contact.
Manual searching checks every item, which is slow for big lists.
Binary search splits the list and checks the middle to find items faster.
Recursive binary search repeats this splitting until it finds the target or confirms it's not there.
Practice
binary search recursive approach?Solution
Step 1: Understand binary search logic
Binary search works by repeatedly dividing the search range in half to find the target efficiently.Step 2: Recognize recursive approach
The recursive approach calls the same function on the half where the target might be, until found or range is empty.Final Answer:
Divide the search range in half recursively until the target is found or range is empty -> Option AQuick Check:
Binary search recursive = divide and conquer [OK]
- Thinking binary search checks every element
- Confusing recursion with iteration
- Assuming array must be sorted during search
Solution
Step 1: Identify parameters for recursion
Recursive binary search needs the array slice, target, and current low and high indices to narrow search.Step 2: Match correct signature
fn binary_search(arr: &[i32], target: i32, low: usize, high: usize) -> Option<usize> matches this with slice reference, target, low and high indices, and returns Option with found index.Final Answer:
fn binary_search(arr: &[i32], target: i32, low: usize, high: usize) -> Option<usize> -> Option CQuick Check:
Recursive binary search needs low and high indices [OK]
- Using Vec instead of slice reference
- Missing low and high parameters for recursion
- Returning wrong type like bool or i32
fn binary_search(arr: &[i32], target: i32, low: usize, high: usize) -> Option<usize> {
if low > high {
return None;
}
let mid = low + (high - low) / 2;
if arr[mid] == target {
return Some(mid);
} else if arr[mid] > target {
return binary_search(arr, target, low, mid - 1);
} else {
return binary_search(arr, target, mid + 1, high);
}
}
fn main() {
let arr = [2, 4, 6, 8, 10];
let result = binary_search(&arr, 6, 0, arr.len() - 1);
println!("{:?}", result);
}Solution
Step 1: Trace initial call and mid calculation
Initial call: low=0, high=4, mid=2. arr[2] = 6 matches target 6.Step 2: Return index wrapped in Some
Since arr[mid] == target, function returns Some(2) immediately.Final Answer:
Some(2) -> Option BQuick Check:
Target found at index 2 [OK]
- Miscomputing mid index
- Confusing index with value
- Forgetting zero-based indexing
fn binary_search(arr: &[i32], target: i32, low: usize, high: usize) -> Option<usize> {
if low >= high {
return None;
}
let mid = low + (high - low) / 2;
if arr[mid] == target {
return Some(mid);
} else if arr[mid] > target {
return binary_search(arr, target, low, mid - 1);
} else {
return binary_search(arr, target, mid + 1, high);
}
}Solution
Step 1: Analyze base case condition
Base case currently returns None if low >= high, but when low == high, the element at that index should still be checked.Step 2: Correct base case to low > high
Changing condition to low > high ensures the last element is checked before returning None.Final Answer:
The base case condition should be low > high, not low >= high -> Option DQuick Check:
Base case must allow low == high check [OK]
- Stopping search too early by wrong base case
- Ignoring possibility of single element left
- Misusing mid calculation causing overflow
Solution
Step 1: Understand duplicates and first occurrence
Duplicates mean target may appear multiple times; first occurrence is the smallest index with target.Step 2: Modify recursion to search left half after finding target
When target is found at mid, recursively search left half to check for earlier occurrence, else return mid.Final Answer:
When target is found, continue searching left half recursively to find earlier occurrence -> Option AQuick Check:
Find first occurrence by searching left after match [OK]
- Stopping at first found index ignoring duplicates
- Sorting array again unnecessarily
- Switching to iterative without reason
Ready to prove it?
Pass the test and this pattern moves unknown
