Bird
Raised Fist0
DSA Pythonprogramming~10 mins

Binary Search Recursive Approach in DSA Python - Execution Trace

Choose your learning style10 modes available
Concept Flow - Binary Search Recursive Approach
Start with full array
↓
Calculate middle index
↓
Compare middle element with target
↓
Equal?
↓
Return mid
↓
Search right half
↓
Repeat steps
↓
Not found? Return -1
Start with the whole array, find the middle element, compare it with the target, then recursively search the left or right half until found or no elements remain.
Execution Sample
DSA Python
def binary_search(arr, target, low, high):
    if low > high:
        return -1
    mid = (low + high) // 2
    if arr[mid] == target:
        return mid
    elif target < arr[mid]:
        return binary_search(arr, target, low, mid - 1)
    else:
        return binary_search(arr, target, mid + 1, high)
This code recursively searches for a target value in a sorted array by dividing the search range in half each time.
Execution Table
StepOperationlowhighmidarr[mid]ComparisonActionResult/Return
1Start search06377 == 5?No, 5 < 7Search left half (low=0, high=2)
2Recursive call02133 == 5?No, 5 > 3Search right half (low=2, high=2)
3Recursive call22255 == 5?YesReturn index 2
4End------Found target at index 2
💡 Search ends when target is found or low > high (no elements left). Here, target found at index 2.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
low00022
high66222
mid-3122
arr[mid]-7355
Key Moments - 3 Insights
Why do we check if low > high at the start?
Because when low becomes greater than high, it means the search range is empty and the target is not in the array. This is shown in execution_table row 1 where the condition stops recursion if true.
Why do we calculate mid as (low + high) // 2?
This finds the middle index of the current search range to split the array in half. See execution_table rows 1-3 where mid changes as low and high change.
Why do we recurse on left half when target < arr[mid]?
Because the array is sorted, if target is less than middle element, it can only be in the left half. This is shown in execution_table row 1 where action is 'Search left half'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of mid at step 2?
A1
B2
C3
D0
💡 Hint
Check the 'mid' column in execution_table row 2.
At which step does the function return the target index?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for the row where 'Comparison' is 'Yes' and 'Result/Return' is an index.
If the target was 8 instead of 5, what would happen at step 1?
ASearch left half
BSearch right half
CReturn index 3
DReturn -1 immediately
💡 Hint
Compare target 8 with arr[mid] = 7 at step 1 in execution_table.
Concept Snapshot
Binary Search Recursive Approach:
- Input: sorted array, target, low, high indices
- Calculate mid = (low + high) // 2
- If arr[mid] == target, return mid
- If target < arr[mid], search left half recursively
- Else, search right half recursively
- Stop when low > high (target not found, return -1)
Full Transcript
Binary Search Recursive Approach starts by checking if the search range is valid (low <= high). It calculates the middle index and compares the middle element with the target. If equal, it returns the index. If the target is smaller, it searches the left half recursively. If larger, it searches the right half recursively. This process repeats until the target is found or the search range is empty, returning -1 if not found.

Practice

(1/5)
1. What is the main idea behind the binary search recursive approach?
easy
A. Search every element one by one from start to end
B. Sort the list first and then search linearly
C. Divide the list into halves and search recursively in the half where the target may exist
D. Use a queue to store elements and search iteratively

Solution

  1. Step 1: Understand binary search logic

    Binary search works by dividing the list into two halves and deciding which half to search next based on comparison with the middle element.
  2. Step 2: Recognize recursive approach

    The recursive approach calls the same function on the half where the target could be, reducing the search space each time.
  3. Final Answer:

    Divide the list into halves and search recursively in the half where the target may exist -> Option C
  4. Quick Check:

    Binary search = divide and conquer [OK]
Hint: Think divide and conquer, search half recursively [OK]
Common Mistakes:
  • Searching all elements linearly instead of dividing
  • Not reducing the search space correctly
  • Confusing iterative with recursive approach
2. Which of the following is the correct base case for a recursive binary search function in Python?
easy
A. if low > high: return -1
B. if low == high: return mid
C. if mid == target: return low
D. if high < low: return mid

Solution

  1. Step 1: Identify base case condition

    The base case occurs when the search space is empty, meaning low index is greater than high index.
  2. Step 2: Confirm correct return value

    When low > high, the target is not found, so return -1 to indicate failure.
  3. Final Answer:

    if low > high: return -1 -> Option A
  4. Quick Check:

    Empty search space means return -1 [OK]
Hint: Base case: low index passes high index means not found [OK]
Common Mistakes:
  • Returning mid when low == high without checking target
  • Using wrong comparison operators in base case
  • Returning wrong index or value in base case
3. What will be the output of the following code?
def binary_search(arr, low, high, target):
    if low > high:
        return -1
    mid = (low + high) // 2
    if arr[mid] == target:
        return mid
    elif arr[mid] > target:
        return binary_search(arr, low, mid - 1, target)
    else:
        return binary_search(arr, mid + 1, high, target)

arr = [2, 4, 6, 8, 10]
print(binary_search(arr, 0, len(arr) - 1, 6))
medium
A. 1
B. 2
C. -1
D. 3

Solution

  1. Step 1: Trace initial call

    Call binary_search(arr, 0, 4, 6). mid = (0+4)//2 = 2. arr[2] = 6 matches target 6.
  2. Step 2: Return mid index

    Since arr[mid] == target, function returns 2 immediately.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    Target 6 found at index 2 [OK]
Hint: Check middle element first, return index if match [OK]
Common Mistakes:
  • Calculating mid incorrectly
  • Returning wrong index
  • Confusing target value with index
4. Find the error in the following recursive binary search code:
def binary_search(arr, low, high, target):
    if low >= high:
        return -1
    mid = (low + high) // 2
    if arr[mid] == target:
        return mid
    elif arr[mid] > target:
        return binary_search(arr, low, mid - 1, target)
    else:
        return binary_search(arr, mid + 1, high, target)
medium
A. Recursive calls should swap low and high parameters
B. Mid calculation should be 'mid = (low + high + 1) // 2'
C. Return value should be 'None' instead of '-1'
D. Base case condition should be 'if low > high' instead of 'if low >= high'

Solution

  1. Step 1: Analyze base case condition

    The base case incorrectly uses 'if low >= high', which misses the case when low == high and target is at that index.
  2. Step 2: Correct base case to 'if low > high'

    Changing to 'if low > high' allows checking the last element when low == high before returning -1.
  3. Final Answer:

    Base case condition should be 'if low > high' instead of 'if low >= high' -> Option D
  4. Quick Check:

    Base case must allow checking last element [OK]
Hint: Base case: low > high means search ended [OK]
Common Mistakes:
  • Using >= instead of > in base case
  • Incorrect mid calculation
  • Returning wrong value on failure
5. Given a sorted list arr = [1, 3, 5, 7, 9, 11, 13], write a recursive binary search function to find the index of the target 10. What will be the final output?
hard
A. -1
B. 4
C. 5
D. 6

Solution

  1. Step 1: Trace recursive calls for target 10

    Initial call: low=0, high=6, mid=3, arr[3]=7 < 10, search right half (4 to 6). Next mid=5, arr[5]=11 > 10, search left half (4 to 4). Next mid=4, arr[4]=9 < 10, search right half (5 to 4). Now low=5 > high=4, base case reached.
  2. Step 2: Return -1 as target not found

    Since low > high, function returns -1 indicating target 10 is not in the list.
  3. Final Answer:

    -1 -> Option A
  4. Quick Check:

    Target 10 not in list returns -1 [OK]
Hint: If target not found, recursive calls end with -1 [OK]
Common Mistakes:
  • Assuming closest smaller element index is returned
  • Not handling base case properly
  • Confusing index with value
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