Here's a more efficient version of binary search with several optimizations:
def binary_search_optimized(arr, target):
"""
Optimized binary search implementation.
Args:
arr: A sorted list of comparable elements
target: The element to search for
Returns:
The index of the target element if found, otherwise -1
"""
left = 0
right = len(arr) - 1
# Early exit for empty array or out-of-bounds target
if not arr or target < arr[0] or target > arr[right]:
return -1
while left <= right:
# Avoid overflow for very large arrays
mid = left + ((right - left) >> 1) # Bit shift is faster than division
mid_val = arr[mid]
if mid_val == target:
return mid
elif mid_val < target:
left = mid + 1
else:
right = mid - 1
return -1
def binary_search_first_occurrence(arr, target):
"""
Find the first occurrence of a target in an array with duplicates.
More efficient than finding any occurrence then scanning backwards.
"""
left = 0
right = len(arr) - 1
result = -1
while left <= right:
mid = left + ((right - left) >> 1)
if arr[mid] == target:
result = mid
right = mid - 1 # Continue searching in the left half
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return result
def binary_search_range(arr, target):
"""
Find both first and last occurrence of target in O(log n) time.
More efficient than two separate searches.
"""
def find_bound(is_first):
left, right = 0, len(arr) - 1
result = -1
while left <= right:
mid = left + ((right - left) >> 1)
if arr[mid] == target:
result = mid
if is_first:
right = mid - 1
else:
left = mid + 1
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return result
return find_bound(True), find_bound(False)
# For very large datasets, you might want to use interpolation search
def interpolation_search(arr, target):
"""
Interpolation search - can be O(log log n) for uniformly distributed data.
Falls back to binary search behavior for non-uniform data.
"""
left = 0
right = len(arr) - 1
while left <= right and arr[left] <= target <= arr[right]:
# If all elements are the same, avoid division by zero
if arr[left] == arr[right]:
return left if arr[left] == target else -1
# Estimate position based on value distribution
pos = left + int((target - arr[left]) * (right - left) /
(arr[right] - arr[left]))
if arr[pos] == target:
return pos
elif arr[pos] < target:
left = pos + 1
else:
right = pos - 1
return -1
# Example usage with performance comparison
if __name__ == "__main__":
import time
# Generate a large sorted array
arr = list(range(0, 10000000, 2)) # Even numbers from 0 to 9,999,998
target = 5000000
# Time the optimized version
start = time.perf_counter()
result = binary_search_optimized(arr, target)
end = time.perf_counter()
print(f"Optimized binary search: {(end - start) * 1000000:.2f} microseconds")
# For uniformly distributed data, interpolation search can be faster
start = time.perf_counter()
result = interpolation_search(arr, target)
end = time.perf_counter()
print(f"Interpolation search: {(end - start) * 1000000:.2f} microseconds")