How can I implement a binary search algorithm in Python?
How can I implement a binary search algorithm in Python?
How can I implement a binary search algorithm in Python?
solveurit24@gmail.com Changed status to publish February 13, 2025
def binary_search(arr, target):
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# Example usage:
arr = [2, 4, 6, 8, 10]
target = 6
index = binary_search(arr, target)
print(f"Element found at index {index}") # Output: Element found at index 2solveurit24@gmail.com Changed status to publish February 13, 2025