Sure! Binary search is an efficient algorithm for finding a specific value (the "target") in a sorted list (array). It works by repeatedly dividing the search interval in half, which makes it much faster than linear search for large datasets (time complexity: O(log n)).
Python has a built-in module called bisect that can perform binary search, but if you want to implement it from scratch (which is a great learning exercise), I'll show you how below. I'll provide an iterative version, as it's straightforward and avoids recursion depth issues for very large lists.
Preconditions
The input list (arr) must be sorted in ascending order.
If the target is found, we return its index.
If not found, we return -1 (a common convention).
Binary Search Implementation in Python
Here's a simple function:
python
def binary_search(arr, target):
"""
Performs binary search on a sorted list to find the target value.
:param arr: A sorted list of elements (ascending order).
:param target: The value to search for.
:return: Index of the target if found, else -1.
"""
low = 0 # Starting index of the search range
high = len(arr) - 1 # Ending index of the search range
while low <= high:
mid = (low + high) // 2 # Calculate the middle index (integer division)
if arr[mid] == target: # Target found!
return mid
elif arr[mid] < target: # Target is in the right half
low = mid + 1
else: # Target is in the left half
high = mid - 1
return -1 # Target not found
How It Works (Step-by-Step Explanation)
Initialize pointers: low starts at the beginning (index 0), and high at the end (index len(arr) - 1).
Loop while there's a valid range (low <= high):
Calculate the middle index: mid = (low + high) // 2. This uses integer division to avoid floats.
Compare arr[mid] with the target:
If equal, return mid (found it!).
If arr[mid] < target, ignore the left half (set low = mid + 1).
If arr[mid] > target, ignore the right half (set high = mid - 1).
If the loop ends without finding the target, return -1.
This halves the search space each time, which is why it's O(log n).
Note: To avoid integer overflow in very large lists, you could calculate mid as mid = low + (high - low) // 2, but in Python 3, integers are unbounded, so it's not strictly necessary.
Example Usage
python
# Sorted list
my_list = [1, 3, 5, 7, 9, 11, 13]
# Search for 7 (should return index 3)
index = binary_search(my_list, 7)
print(f"Target found at index: {index}") # Output: Target found at index: 3
# Search for 10 (not in list, should return -1)
index = binary_search(my_list, 10)
print(f"Target found at index: {index}") # Output: Target found at index: -1
Testing It Yourself
Copy the code into a Python file or interpreter and run it. Try with different sorted lists to see how it behaves. If the list isn't sorted, the results will be incorrect—so always sort first if needed (e.g., using arr.sort()).
Recursive Version (Optional)
If you prefer recursion, here's a quick alternative:
python
def binary_search_recursive(arr, target, low=0, high=None):
if high is None:
high = len(arr) - 1
if low > high:
return -1
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, high)
else:
return binary_search_recursive(arr, target, low, mid - 1)
Usage: index = binary_search_recursive(my_list, 7)
Common Edge Cases to Consider
Empty list: Returns -1.
List with one element: Works if it matches, else -1.
Target at the start/end: Should find it.
Duplicates: Returns one valid index (not necessarily the first).
If you have any questions, want to handle duplicates (e.g., find the first occurrence), or need help with a specific variation, let me know! 😊