Python Program to Find Binary Search Using Recursion
Examples
How to Think About It
Algorithm
Code
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) # Example usage arr = [1, 2, 3, 4, 5] target = 3 result = binary_search(arr, target, 0, len(arr) - 1) print(result)
Dry Run
Let's trace the search for target 3 in the list [1, 2, 3, 4, 5] through the code
Initial call
low=0, high=4, mid=(0+4)//2=2, arr[mid]=3
Check middle element
arr[mid] == target (3 == 3), return mid=2
| Call | low | high | mid | arr[mid] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 4 | 2 | 3 | Found target, return 2 |
Why This Works
Step 1: Divide the list
The function splits the list into halves by calculating the middle index with mid = (low + high) // 2.
Step 2: Compare middle element
It compares the middle element with the target using arr[mid] == target to check if the search is successful.
Step 3: Recursive search
If not found, it calls itself recursively on the left or right half depending on whether the target is smaller or larger than the middle element.
Step 4: Base case
When the search space is empty (low > high), it returns -1 indicating the target is not in the list.
Alternative Approaches
def binary_search_iterative(arr, target): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif target < arr[mid]: high = mid - 1 else: low = mid + 1 return -1 # Example usage arr = [1, 2, 3, 4, 5] target = 3 print(binary_search_iterative(arr, target))
import bisect def binary_search_bisect(arr, target): index = bisect.bisect_left(arr, target) if index != len(arr) and arr[index] == target: return index return -1 # Example usage arr = [1, 2, 3, 4, 5] target = 3 print(binary_search_bisect(arr, target))
Complexity: O(log n) time, O(log n) space
Time Complexity
Binary search divides the search space in half each time, so it runs in logarithmic time, O(log n), where n is the number of elements.
Space Complexity
The recursive approach uses O(log n) space due to the call stack from recursive calls. The iterative approach uses O(1) space.
Which Approach is Fastest?
Both recursive and iterative binary search have the same time complexity, but iterative is more memory efficient. Using Python's bisect module is often fastest in practice due to optimization.
| 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 practical use |
| Python bisect Module | O(log n) | O(1) | Fast, built-in, and simple usage |