Binary Search in Python
Binary search is a classic search algorithm that is commonly used to find a target value within a sorted list. It works by repeatedly dividing the list in half and discarding the half that is guaranteed not to contain the target.
Iterative Version
def binary_search(arr, target): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] < target: low = mid + 1 elif arr[mid] > target: high = mid - 1 else: return mid # target found return -1 # target not found
Recursive Version
def recursive_binary_search(arr, target, low=0, high=None): if high is None: high = len(arr) - 1 if low <= high: mid = (low + high) // 2 if arr[mid] < target: return recursive_binary_search(arr, target, mid + 1, high) elif arr[mid] > target: return recursive_binary_search(arr, target, low, mid - 1) else: return mid # target found return -1 # target not found
In both versions, the function will return the index of the target if it's found in the list, and -1 if it's not.