Bird
Raised Fist0
DSA C++programming~10 mins

Binary Search Recursive Approach in DSA C++ - Execution Trace

Choose your learning style10 modes available
Concept Flow - Binary Search Recursive Approach
Start with full array range
↓
Calculate middle index
↓
Compare middle element with target
↓
Return mid
↓
Repeat until found or range invalid
↓
Return -1 if not found
Start with the full array, find the middle element, compare it with the target, then recursively search the left or right half until found or range is invalid.
Execution Sample
DSA C++
int binarySearch(int arr[], int left, int right, int target) {
  if (left > right) return -1;
  int mid = left + (right - left) / 2;
  if (arr[mid] == target) return mid;
  if (arr[mid] > target) return binarySearch(arr, left, mid - 1, target);
  return binarySearch(arr, mid + 1, right, target);
}
This code recursively searches for a target value in a sorted array by dividing the search range in half each time.
Execution Table
StepOperationLeftRightMidarr[Mid]ComparisonNext RangeResult
1Start search06377 vs 3: 7 > 3Left half (0 to 2)
2Recursive call02133 vs 3: 3 == 3Found targetReturn 1
3Return1
💡 Search ends when target is found at index 1 or when left > right (not in this case).
Variable Tracker
VariableStartAfter Step 1After Step 2Final
left0000
right6222
midN/A311
arr[mid]N/A733
resultN/AN/A11
Key Moments - 3 Insights
Why do we calculate mid as left + (right - left) / 2 instead of (left + right) / 2?
Calculating mid as left + (right - left) / 2 prevents integer overflow when left and right are large, as shown in Step 1 of the execution_table.
What happens when left becomes greater than right?
When left > right, it means the target is not in the array, so the function returns -1 and stops recursion, as explained in the exit_note.
Why do we return mid immediately when arr[mid] == target?
Because we found the target at index mid, so no further search is needed. This is shown in Step 2 where the comparison is equal and the function returns mid.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of mid at Step 1?
A1
B2
C3
D0
💡 Hint
Check the 'Mid' column in the first row of the execution_table.
At which step does the function find the target value?
AStep 1
BStep 2
CStep 3
DIt never finds the target
💡 Hint
Look at the 'Comparison' and 'Result' columns in the execution_table.
If the target was 10 instead of 3, what would happen at Step 1?
ASearch right half (4 to 6)
BSearch left half (0 to 2)
CReturn mid immediately
DReturn -1 immediately
💡 Hint
Compare arr[mid] with target in Step 1 and decide which half to search next.
Concept Snapshot
Binary Search Recursive Approach:
- Input: sorted array, left index, right index, target
- Calculate mid = left + (right - left) / 2
- If arr[mid] == target, return mid
- If arr[mid] > target, search left half recursively
- Else, search right half recursively
- Return -1 if target not found (left > right)
Full Transcript
Binary Search Recursive Approach starts by checking the middle element of the current search range. If the middle element equals the target, it returns the index immediately. If the middle element is greater than the target, it recursively searches the left half. If less, it searches the right half. This process repeats until the target is found or the search range is invalid (left > right), returning -1. The mid index is calculated carefully to avoid overflow. The execution table shows the step-by-step recursive calls and comparisons.

Practice

(1/5)
1. What is the main idea behind the binary search recursive approach?
easy
A. Use recursion to reverse the array before searching
B. Divide the array into halves and search recursively in the relevant half
C. Sort the array recursively before searching
D. Search every element one by one recursively

Solution

  1. Step 1: Understand binary search logic

    Binary search works by dividing the array into two halves and deciding which half to search next based on the middle element.
  2. Step 2: Apply recursion in binary search

    Recursion calls the same function on the half where the target might be, reducing the search space each time.
  3. Final Answer:

    Divide the array into halves and search recursively in the relevant half -> Option B
  4. Quick Check:

    Binary search = divide and conquer [OK]
Hint: Think divide and conquer, search half each time [OK]
Common Mistakes:
  • Searching all elements recursively instead of half
  • Sorting inside the search function
  • Not reducing search space correctly
2. Which of the following is the correct base case for a recursive binary search function in C++?
easy
A. if (start > end) return -1;
B. if (start == end) return start;
C. if (start < end) return -1;
D. if (start == 0) return 0;

Solution

  1. Step 1: Identify when search should stop

    The search should stop when the start index is greater than the end index, meaning the element is not found.
  2. Step 2: Confirm base case condition

    Checking if start > end returns -1 to indicate the target is missing.
  3. Final Answer:

    if (start > end) return -1; -> Option A
  4. Quick Check:

    Base case = start > end means not found [OK]
Hint: Stop when start passes end, return -1 [OK]
Common Mistakes:
  • Using start == end as base case incorrectly
  • Returning wrong index when not found
  • Confusing start and end conditions
3. What will be the output of the following C++ code?
int binarySearch(int arr[], int start, int end, int target) {
  if (start > end) return -1;
  int mid = start + (end - start) / 2;
  if (arr[mid] == target) return mid;
  else if (arr[mid] > target) return binarySearch(arr, start, mid - 1, target);
  else return binarySearch(arr, mid + 1, end, target);
}

int main() {
  int arr[] = {2, 4, 6, 8, 10};
  int index = binarySearch(arr, 0, 4, 6);
  std::cout << index;
  return 0;
}
medium
A. 2
B. 1
C. 3
D. -1

Solution

  1. Step 1: Identify the target and array

    The array is {2,4,6,8,10} and target is 6.
  2. Step 2: Trace recursive calls

    First mid = 2 (index 2), arr[2] = 6 matches target, so return 2 immediately.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    Target 6 found at index 2 [OK]
Hint: Check middle element first, return index if match [OK]
Common Mistakes:
  • Confusing index with value
  • Off-by-one errors in mid calculation
  • Not returning correct index
4. Find the error in this recursive binary search function:
int binarySearch(int arr[], int start, int end, int target) {
  if (start >= end) return -1;
  int mid = (start + end) / 2;
  if (arr[mid] == target) return mid;
  else if (arr[mid] > target) return binarySearch(arr, start, mid - 1, target);
  else return binarySearch(arr, mid + 1, end, target);
}
medium
A. Mid calculation should be start - end instead of start + end
B. Return value should be target, not index
C. Base case condition should be start > end, not start >= end
D. Recursive calls should swap start and end

Solution

  1. Step 1: Analyze base case condition

    The base case incorrectly uses start >= end, which misses checking when start == end.
  2. Step 2: Correct base case for full search

    It should be start > end to allow checking the last element at start == end.
  3. Final Answer:

    Base case condition should be start > end, not start >= end -> Option C
  4. Quick Check:

    Base case = start > end to stop [OK]
Hint: Base case must allow start == end check [OK]
Common Mistakes:
  • Using >= instead of > in base case
  • Wrong mid calculation formula
  • Returning wrong values
5. Given a sorted array with possible duplicate elements, how can you modify the recursive binary search to find the first occurrence of a target value?
hard
A. Use linear search after binary search to find first occurrence
B. Return mid immediately when arr[mid] == target
C. Search right half only when arr[mid] == target
D. When arr[mid] == target, continue searching left half to find earlier occurrence

Solution

  1. Step 1: Understand duplicates in sorted array

    Duplicates mean target can appear multiple times; we want the first index.
  2. Step 2: Modify recursive search on match

    When arr[mid] == target, recursively search left half to check for earlier occurrence, else return mid.
  3. Step 3: Implement logic

    If left recursive call returns valid index, return it; otherwise return mid.
  4. Final Answer:

    When arr[mid] == target, continue searching left half to find earlier occurrence -> Option D
  5. Quick Check:

    Find first occurrence = search left on match [OK]
Hint: On match, search left half to find first occurrence [OK]
Common Mistakes:
  • Returning first found index without checking left side
  • Searching right half on match
  • Using linear search unnecessarily
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