Question: How can you implement a binary search algorithm in Python?
Response 1:
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Response 2:
def binary_search(arr, x):
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
left = mid + 1
else:
right = mid - 1
return -1
Response 3:
def binary_search(lst, value):
start, end = 0, len(lst) - 1
while start <= end:
mid = start + (end - start) // 2
if lst[mid] == value:
return mid
elif lst[mid] < value:
start = mid + 1
else:
end = mid - 1
return -1
Final Answer:
def binary_search(arr, target):
left, right = 0, len(arr) - 1 # Use descriptive variable names
while left <= right:
mid = left + (right - left) // 2 # Calculate middle index to avoid integer overflow
if arr[mid] == target: # Check if the target is found
return mid
elif arr[mid] < target: # If the target is greater, move left boundary to mid + 1
left = mid + 1
else: # If the target is smaller, move right boundary to mid - 1
right = mid - 1
return -1 # Return -1 if the target is not found in the array
The final answer combines the best elements from all three responses, using descriptive variable names, avoiding integer overflow while calculating the middle index, and providing clear explanations for each step of the algorithm.