Binary Search Recursive Approach in DSA C# - Time & Space Complexity
We want to understand how the time taken by recursive binary search changes as the input size grows.
Specifically, how many steps does it take to find an item in a sorted list?
Analyze the time complexity of the following code snippet.
public int BinarySearch(int[] arr, int target, int left, int right)
{
if (left > right) return -1;
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] > target) return BinarySearch(arr, target, left, mid - 1);
else return BinarySearch(arr, target, mid + 1, right);
}
This code searches for a target value in a sorted array by repeatedly dividing the search range in half.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive call that halves the search range each time.
- How many times: At most, the function calls itself until the range is empty, roughly halving the size each time.
Each recursive step cuts the search area in half, so the number of steps grows slowly as the input size grows.
| 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 number of steps grows slowly, increasing by one step each time the input size doubles.
[X] Wrong: "Binary search checks every element one by one, so it is O(n)."
[OK] Correct: Binary search skips half the elements each step, so it does not check all elements, making it much faster than linear search.
Understanding binary search's time complexity shows you can analyze efficient algorithms that use divide and conquer, a key skill in many coding challenges.
"What if the array was not sorted? How would the time complexity of searching change?"
Practice
Binary Search Recursive Approach when searching for a value in a sorted array?Solution
Step 1: Understand binary search logic
Binary search works by dividing the sorted array into two halves and deciding which half to search next based on the middle element.Step 2: Recognize recursive approach
The recursive approach calls the same search function on the half where the target value may exist, reducing the search space each time.Final Answer:
Divide the array into halves and search recursively in the half where the value can be. -> Option DQuick Check:
Binary search = divide and conquer [OK]
- Thinking binary search checks every element linearly
- Not realizing array must be sorted first
- Confusing iterative and recursive approaches
Solution
Step 1: Identify base case meaning
The base case stops recursion when the search space is invalid, meaning start index is greater than end index.Step 2: Match condition to code
The conditionif (start > end) return -1;correctly indicates the target is not found.Final Answer:
if (start > end) return -1; -> Option CQuick Check:
Base case = invalid range returns -1 [OK]
- Using wrong comparison like start == end as base case
- Returning 0 which can be a valid index
- Not handling base case causing infinite recursion
int[] arr = {2, 4, 6, 8, 10};
int result = BinarySearch(arr, 0, arr.Length - 1, 6);
Console.WriteLine(result);
int BinarySearch(int[] array, int start, int end, int target) {
if (start > end) return -1;
int mid = (start + end) / 2;
if (array[mid] == target) return mid;
else if (array[mid] > target) return BinarySearch(array, start, mid - 1, target);
else return BinarySearch(array, mid + 1, end, target);
}Solution
Step 1: Trace initial call and mid calculation
Initial call: start=0, end=4, mid=(0+4)/2=2. array[2]=6 matches target 6.Step 2: Return mid index
Since array[mid] == target, function returns 2 immediately.Final Answer:
2 -> Option AQuick Check:
Target found at index 2 [OK]
- Miscomputing mid index
- Returning wrong index due to off-by-one errors
- Confusing array values with indices
int BinarySearch(int[] array, int start, int end, int target) {
if (start >= end) return -1;
int mid = (start + end) / 2;
if (array[mid] == target) return mid;
else if (array[mid] > target) return BinarySearch(array, start, mid - 1, target);
else return BinarySearch(array, mid + 1, end, target);
}Solution
Step 1: Analyze base case condition
The base case usesstart >= end, which wrongly excludes the case when start == end, missing the last element check.Step 2: Correct base case to allow checking when start == end
Changing tostart > endensures the last element is checked before stopping recursion.Final Answer:
Change base case to if (start > end) return -1; -> Option BQuick Check:
Base case must allow start == end check [OK]
- Stopping recursion too early with wrong base case
- Changing mid calculation unnecessarily
- Returning 0 which can be a valid index
Solution
Step 1: Understand duplicates and first occurrence
Duplicates mean target can appear multiple times; to find first occurrence, we must check if earlier indices also have the target.Step 2: Modify recursion to search left half when target found
When array[mid] == target, recursively search left half to find if target appears earlier; if none found, return current mid.Final Answer:
When array[mid] == target, continue searching left half to find earlier occurrence. -> Option AQuick Check:
Find first occurrence by searching left half on match [OK]
- Returning first found index without checking left side
- Searching right half on match which finds last occurrence
- Using linear search after binary search unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
