Junior — Middle
What temporal difficulty does the binary search algorithm have?
sobes.tech AI
Answer from AI
The binary search algorithm has a time complexity of O(log n), where n is the number of elements in the sorted array.
This means that with each step, the search area is halved, which is significantly more efficient than linear search with O(n).
Example in Python:
def binary_search(arr, target):
left, right = 0, 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