Certainly! Here's a simple implementation of binary search in Python. Binary search works on a sorted list by repeatedly dividing the search interval in half.
Iterative Binary Search
python
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid # Return the index where target is found
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Target not found
Recursive Binary Search
python
def binary_search_recursive(arr, target, left, right):
if left > right:
return -1 # Base case: target not found
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, right)
else:
return binary_search_recursive(arr, target, left, mid - 1)
Example usage:
python
arr = [1, 3, 5, 7, 9, 11]
target = 7
# Iterative
index = binary_search(arr, target)
print(f"Iterative: Element found at index {index}")
# Recursive
index = binary_search_recursive(arr, target, 0, len(arr) - 1)
print(f"Recursive: Element found at index {index}")
If you want, I can also help with binary search variants or explain how it works step-by-step!
User
Make the code more efficient!
Assistant
Binary search is already quite efficient with a time complexity of O(log n), which is optimal for searching in a sorted array. However, there are a few small improvements and best practices you can apply to the code for clarity, safety, and slight performance gains:
1. Avoid potential overflow in mid calculation (mostly relevant in other languages, but good practice)
Instead of:
python
mid = (left + right) // 2
Use:
python
mid = left + (right - left) // 2
This prevents integer overflow in languages like C++ or Java (not an issue in Python, but good habit).
2. Use bisect module (built-in, highly optimized)
Python’s standard library has a bisect module that implements binary search efficiently in C.
3. Avoid repeated attribute lookups or function calls inside loops (minor optimization)
Optimized Iterative Binary Search
python
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2 # safer mid calculation
mid_val = arr[mid] # avoid repeated indexing
if mid_val == target:
return mid
elif mid_val < target:
left = mid + 1
else:
right = mid - 1
return -1
Using Python’s built-in bisect module
python
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
Summary:
The algorithmic complexity can’t be improved beyond O(log n).
Use mid = left + (right - left) // 2 for safety.
Use bisect for a highly optimized built-in solution.
Minor micro-optimizations like caching arr[mid] in a variable.
If you want, I can also help you with binary search on more complex data structures or with approximate matches!