This makes for an interesting test. I checked Claude Sonnet, just for the he'll of it
Prompt:
Please write a bug free binary search in python
Answer:
def binary_search(arr, target):
"""
Performs binary search on a sorted array.
Args:
arr: A sorted list of comparable elements
target: The element to search for
Returns:
The index of target if found, -1 otherwise
"""
left = 0
right = len(arr) - 1
while left <= right:
# Avoid potential overflow by using this formula
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# Example usage and test cases
if __name__ == "__main__":
# Test cases
test_array = [1, 3, 5, 7, 9, 11, 13, 15]
print(binary_search(test_array, 7)) # Output: 3
print(binary_search(test_array, 1)) # Output: 0
print(binary_search(test_array, 15)) # Output: 7
print(binary_search(test_array, 4)) # Output: -1
print(binary_search([], 5)) # Output: -1
print(binary_search([5], 5)) # Output: 0
print(binary_search([5], 3)) # Output: -1