python
Published on January 26, 2024By DeveloperBreeze
# Function to perform binary search on a sorted array
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
# Usage: Perform binary search on a sorted array
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 5
result = binary_search(arr, target)
Comments
Please log in to leave a comment.