Bird
Raised Fist0
DSA Rustprogramming~10 mins

Binary Search Iterative Approach in DSA Rust - Execution Trace

Choose your learning style10 modes available
Concept Flow - Binary Search Iterative Approach
Start with sorted array and target
↓
Set low = 0, high = array length - 1
↓
While low <= high
↓
Calculate mid = (low + high) / 2
↓
Compare array[mid
↓
Return mid
↓
Repeat loop or exit if low > high
↓
Return -1 if not found
This flow shows how binary search narrows down the search range by adjusting low and high pointers until the target is found or the range is empty.
Execution Sample
DSA Rust
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
}
This code performs an iterative binary search on a sorted array to find the target's index or returns -1 if not found.
Execution Table
StepOperationlowhighmidarr[mid]ComparisonActionSearch Range Visual
1Initialize low and high06---Start search[1, 3, 5, 7, 9, 11, 13]
2Calculate mid06377 == 7Return mid = 3[1, 3, 5, 7, 9, 11, 13]
ExitTarget found06377 == 7Stop search[1, 3, 5, 7, 9, 11, 13]
💡 Target 7 found at index 3, search ends.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
low0000
high6666
mid--33
Key Moments - 3 Insights
Why do we calculate mid as low + (high - low) / 2 instead of (low + high) / 2?
Calculating mid as low + (high - low) / 2 prevents integer overflow when low and high are large, as shown in step 2 of the execution_table.
Why does the loop continue only while low <= high?
The loop continues while low <= high to ensure all possible positions are checked. When low > high, the search range is empty, so the target is not found, as shown by the exit condition.
What happens if the target is not in the array?
If the target is not found, low will eventually become greater than high, ending the loop and returning -1, indicating the target is absent.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the value of mid?
A3
B0
C6
D7
💡 Hint
Check the 'mid' column in execution_table row with Step 2.
At which step does the search stop because the target is found?
AStep 1
BStep 2
CExit
DStep 3
💡 Hint
Look at the 'Action' column where it says 'Return mid = 3'.
If the target was 10 instead of 7, what would happen to the 'low' pointer after the first comparison?
AIt would stay at 0
BIt would become 4
CIt would become 3
DIt would become 6
💡 Hint
Refer to the 'Action' column logic where arr[mid] < target causes low = mid + 1.
Concept Snapshot
Binary Search Iterative Approach:
- Works on sorted arrays
- Use low and high pointers to track search range
- Calculate mid = low + (high - low) / 2
- Compare arr[mid] with target
- If equal, return mid
- If arr[mid] < target, move low to mid + 1
- Else, move high to mid - 1
- Repeat until low > high
- Return -1 if not found
Full Transcript
Binary search is a method to find a target value in a sorted array by repeatedly dividing the search range in half. We start with two pointers: low at the start and high at the end of the array. We calculate the middle index mid safely as low plus half the distance to high. We compare the middle element with the target. If they match, we return the mid index. If the middle element is less than the target, we move low to mid plus one to search the right half. Otherwise, we move high to mid minus one to search the left half. This process repeats until low exceeds high, meaning the target is not in the array, and we return -1. This approach is efficient and runs in logarithmic time.

Practice

(1/5)
1. What is the main purpose of the binary search iterative approach in a sorted array?
easy
A. To find the position of a target value efficiently by repeatedly dividing the search interval in half
B. To sort the array elements in ascending order
C. To reverse the array elements
D. To find the maximum value in the array

Solution

  1. 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.
  2. Step 2: Compare with other options

    Sorting, reversing, or finding max are different operations unrelated to binary search's main goal.
  3. Final Answer:

    To find the position of a target value efficiently by repeatedly dividing the search interval in half -> Option A
  4. Quick Check:

    Binary search = divide and conquer search [OK]
Hint: Binary search halves the search space each step [OK]
Common Mistakes:
  • Confusing binary search with sorting algorithms
  • Thinking binary search works on unsorted arrays
  • Assuming binary search finds max or min values
2. Which of the following is the correct Rust syntax to start the iterative binary search loop over a sorted slice arr with indices low and high?
easy
A. while low <= high { /* loop body */ }
B. for i in low..high { /* loop body */ }
C. loop { if low > high { break; } /* loop body */ }
D. while low < high { /* loop body */ }

Solution

  1. 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.
  2. Step 2: Compare options

    while low <= high { /* loop body */ } uses while 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 */ } uses low < high, which misses the case when low equals high.
  3. Final Answer:

    while low <= high { /* loop body */ } -> Option A
  4. Quick Check:

    Loop condition includes equality for last element [OK]
Hint: Use while low <= high to cover all elements [OK]
Common Mistakes:
  • Using for loop instead of while for binary search
  • Using < instead of <= causing missed element check
  • Using infinite loop without proper break condition
3. What will be the output of the following Rust code snippet using iterative binary search?
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));
}
medium
A. -1
B. 1
C. 2
D. 3

Solution

  1. 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.
  2. Step 2: Confirm returned index

    Index 2 is correct position of 6 in the array.
  3. Final Answer:

    2 -> Option C
  4. Quick Check:

    Target 6 found at index 2 [OK]
Hint: Check mid index value equals target first [OK]
Common Mistakes:
  • Miscomputing mid index causing wrong return
  • Returning -1 incorrectly when target exists
  • Confusing index with value in output
4. Identify the error in this Rust iterative binary search function and choose the fix:
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
}
medium
A. Change while condition to low < high
B. Remove type casting of mid to usize
C. Change mid calculation to mid = low - (high - low) / 2
D. Change high initialization to arr.len() as i32 - 1

Solution

  1. Step 1: Analyze high initialization

    High is set to arr.len() which is out of bounds index (since last valid index is length - 1).
  2. Step 2: Correct high initialization

    Set high to arr.len() - 1 to avoid index out of bounds error during access.
  3. Final Answer:

    Change high initialization to arr.len() as i32 - 1 -> Option D
  4. Quick Check:

    High must be last valid index [OK]
Hint: High index = length - 1 to avoid out of bounds [OK]
Common Mistakes:
  • Setting high to length causing panic
  • Changing while condition incorrectly
  • Incorrect mid calculation formula
5. Given a sorted array 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?
hard
A. 5
B. 4
C. -1
D. 3

Solution

  1. Step 1: Understand problem - find smallest element >= target

    We want the index of the first element not less than target 8.
  2. 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.
  3. Final Answer:

    4 -> Option B
  4. Quick Check:

    First element >= 8 is 9 at index 4 [OK]
Hint: Find first element >= target by adjusting high on match [OK]
Common Mistakes:
  • Returning index of element just less than target
  • Returning -1 when element exists
  • Confusing smallest element greater than target with equal
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard