Python Program for Binary Search Using Recursion
def binary_search(arr, low, high, x): that checks the middle element and recursively searches the left or right half until the element is found or the range is empty.Examples
How to Think About It
Algorithm
Code
def binary_search(arr, low, high, x): if low > high: return -1 mid = (low + high) // 2 if arr[mid] == x: return mid elif x < arr[mid]: return binary_search(arr, low, mid - 1, x) else: return binary_search(arr, mid + 1, high, x) arr = [1, 3, 5, 7, 9] x = 7 result = binary_search(arr, 0, len(arr) - 1, x) print(result)
Dry Run
Let's trace searching for 7 in [1, 3, 5, 7, 9] using recursion.
Initial call
low=0, high=4, mid=2, arr[mid]=5, x=7
Search right half
x > arr[mid], call binary_search(arr, 3, 4, 7)
Second call
low=3, high=4, mid=3, arr[mid]=7, x=7
Found element
arr[mid] == x, return 3
| Call | low | high | mid | arr[mid] | x | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 4 | 2 | 5 | 7 | x > arr[mid], search right half |
| 2 | 3 | 4 | 3 | 7 | 7 | Found element, return index 3 |
Why This Works
Step 1: Divide the list
The code finds the middle index with mid = (low + high) // 2 to split the list into two halves.
Step 2: Compare middle element
It compares arr[mid] with the target x to decide if the search is done or which half to search next.
Step 3: Recursive calls
If the target is not found, the function calls itself with updated low and high to search the correct half, narrowing the search range.
Alternative Approaches
def binary_search_iter(arr, x): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == x: return mid elif x < arr[mid]: high = mid - 1 else: low = mid + 1 return -1 arr = [1, 3, 5, 7, 9] x = 7 print(binary_search_iter(arr, x))
import bisect def binary_search_bisect(arr, x): i = bisect.bisect_left(arr, x) if i != len(arr) and arr[i] == x: return i return -1 arr = [1, 3, 5, 7, 9] x = 7 print(binary_search_bisect(arr, x))
Complexity: O(log n) time, O(log n) space
Time Complexity
Binary search divides the list in half each step, so it takes about log base 2 of n steps to find the element or conclude it's missing.
Space Complexity
Recursive calls add to the call stack, so space used is proportional to the recursion depth, which is O(log n).
Which Approach is Fastest?
Iterative binary search uses O(1) space and is faster in practice due to no recursion overhead, but recursive is easier to understand.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive binary search | O(log n) | O(log n) | Learning recursion and divide-and-conquer |
| Iterative binary search | O(log n) | O(1) | Memory efficient and fast in production |
| bisect module | O(log n) | O(1) | Quick built-in solution for sorted lists |