Binary Search Iterative Approach in DSA Rust - Time & Space Complexity
We want to understand how the time taken by binary search changes as the list size grows.
How many steps does it take to find a number in a sorted list?
Analyze the time complexity of the following code snippet.
fn binary_search(arr: &[i32], target: i32) -> Option<usize> {
let mut left = 0;
let mut right = arr.len().wrapping_sub(1);
while left <= right {
let mid = left + (right - left) / 2;
if arr[mid] == target {
return Some(mid);
} else if arr[mid] < target {
left = mid + 1;
} else {
right = mid.wrapping_sub(1);
}
}
None
}
This code searches for a target number in a sorted list by repeatedly dividing the search range in half.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that halves the search range each time.
- How many times: The loop runs until the search range is empty, roughly halving the range each step.
Each step cuts the list size in half, so the number of steps grows slowly as the list gets bigger.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 steps |
| 100 | About 7 steps |
| 1000 | About 10 steps |
Pattern observation: Doubling the input size adds only one extra step.
Time Complexity: O(log n)
This means the steps needed grow slowly, increasing by one step each time the list size doubles.
[X] Wrong: "Binary search checks every item one by one, so it is O(n)."
[OK] Correct: Binary search does not check every item; it cuts the search area in half each time, so it takes far fewer steps.
Understanding binary search time complexity shows you can analyze efficient algorithms, a key skill in coding interviews and real projects.
"What if the list was not sorted? How would the time complexity change?"
Practice
binary search iterative approach in a sorted array?Solution
Step 1: Understand binary search goal
Binary search aims to find a target value's position in a sorted array quickly by dividing the search range repeatedly.Step 2: Compare with other options
Sorting, reversing, or finding max are different operations unrelated to binary search's main goal.Final Answer:
To find the position of a target value efficiently by repeatedly dividing the search interval in half -> Option AQuick Check:
Binary search = divide and conquer search [OK]
- Confusing binary search with sorting algorithms
- Thinking binary search works on unsorted arrays
- Assuming binary search finds max or min values
arr with indices low and high?Solution
Step 1: Identify correct loop condition for binary search
Binary search continues while low index is less than or equal to high index to cover all elements.Step 2: Compare options
while low <= high { /* loop body */ } useswhile low <= high, which is correct. for i in low..high { /* loop body */ } uses a for loop which is not suitable. loop { if low > high { break; } /* loop body */ } uses an infinite loop with break, which is less clear. while low < high { /* loop body */ } useslow < high, which misses the case when low equals high.Final Answer:
while low <= high { /* loop body */ } -> Option AQuick Check:
Loop condition includes equality for last element [OK]
- Using for loop instead of while for binary search
- Using < instead of <= causing missed element check
- Using infinite loop without proper break condition
fn binary_search(arr: &[i32], target: i32) -> i32 {
let mut low = 0;
let mut high = arr.len() as i32 - 1;
while low <= high {
let mid = low + (high - low) / 2;
if arr[mid as usize] == target {
return mid;
} else if arr[mid as usize] < target {
low = mid + 1;
} else {
high = mid - 1;
}
}
-1
}
fn main() {
let arr = [2, 4, 6, 8, 10];
println!("{}", binary_search(&arr, 6));
}Solution
Step 1: Trace binary search for target 6 in array
Array is [2,4,6,8,10]. Initial low=0, high=4. mid=2. arr[2]=6 equals target, so return 2.Step 2: Confirm returned index
Index 2 is correct position of 6 in the array.Final Answer:
2 -> Option CQuick Check:
Target 6 found at index 2 [OK]
- Miscomputing mid index causing wrong return
- Returning -1 incorrectly when target exists
- Confusing index with value in output
fn binary_search(arr: &[i32], target: i32) -> i32 {
let mut low = 0;
let mut high = arr.len() as i32;
while low <= high {
let mid = (low + high) / 2;
if arr[mid as usize] == target {
return mid;
} else if arr[mid as usize] < target {
low = mid + 1;
} else {
high = mid - 1;
}
}
-1
}Solution
Step 1: Analyze high initialization
High is set to arr.len() which is out of bounds index (since last valid index is length - 1).Step 2: Correct high initialization
Set high to arr.len() - 1 to avoid index out of bounds error during access.Final Answer:
Change high initialization to arr.len() as i32 - 1 -> Option DQuick Check:
High must be last valid index [OK]
- Setting high to length causing panic
- Changing while condition incorrectly
- Incorrect mid calculation formula
arr = [1, 3, 5, 7, 9, 11], write an iterative binary search function in Rust to find the index of the smallest element greater than or equal to a target value. What will be the output of your function when searching for target 8?Solution
Step 1: Understand problem - find smallest element >= target
We want the index of the first element not less than target 8.Step 2: Trace binary search for target 8
Array: [1,3,5,7,9,11]. Elements >=8 are 9 (index 4) and 11 (index 5). The smallest is 9 at index 4.Final Answer:
4 -> Option BQuick Check:
First element >= 8 is 9 at index 4 [OK]
- Returning index of element just less than target
- Returning -1 when element exists
- Confusing smallest element greater than target with equal
Ready to prove it?
Pass the test and this pattern moves unknown
