Binary Search
š Problem Statement
Given a sorted array arr and a target value, return the index of the target using recursive binary search. If not found, return None. Input: arr = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], target = 23 ā Output: 5.
š” Intuition
Binary search exploits sorted order to eliminate half the search space with each comparison. Compare target to the middle element : if equal, found; if , search right half; otherwise left half. Each recursive call works on a shrinking window of size .
š§ Approach
- Base case: if
left > right, return None (target not found). - Calculate .
- If
arr[mid] == target, returnmid. - If
arr[mid] < target, recurse on right:binary_search(arr, target, mid + 1, right). - If
arr[mid] > target, recurse on left:binary_search(arr, target, left, mid - 1).
ā” Complexity Analysis
ā the search space halves with each recursive call
for the recursion stack (one frame per halving step)
ā ļø Common Mistakes
- Using
(left + right) / 2instead of//(returns a float in Python) - Forgetting the base case
left > right, causing infinite recursion - Applying binary search to an unsorted array ā produces incorrect results silently
- Off-by-one: searching left uses
right = mid - 1, right usesleft = mid + 1
šÆ Final Thoughts
Binary search reduces linear search to . For 1 billion elements, that is ~30 comparisons instead of 1 billion. The iterative version (using while) is preferred in practice to avoid the stack overhead.