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.



![Binary search code 2 An educational infographic explaining Binary Search in Python, featuring: Algorithm Steps: Sorted array division, midpoint calculation, and element comparison Python Code Snippet: Clean while loop implementation with low, high, and mid variables Visual Example: Step-by-step search for number 23 in array [2, 5, 8, 12, 23, 38, 56].](https://more-marks.com/wp-content/uploads/2023/07/dW6cUdbkTOsq1gwsh5rQf-683x1024.jpg)