Binary Search
Binary search is an algorithm that searches for a target element in a sorted array by repeatedly dividing the search interval in half.
python
# Binary search function
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
No comments:
Post a Comment