Junior — Middle
Explain the working principle of the binary search algorithm and its main steps.
sobes.tech AI
Answer from AI
Binary search is an efficient algorithm for finding an element in a sorted array. Its principle is to repeatedly divide the search area in half and compare the target value with the middle element.
Main steps:
- Define initial search boundaries: left and right indices.
- Find the middle index: mid = (left + right) // 2.
- Compare the target with the element at mid.
- If equal, return mid.
- If the target is less, move the right boundary to mid - 1.
- If greater, move the left boundary to mid + 1.
- Repeat steps 2-3 until left exceeds right.
If the element is not found, return -1, for example.
Python example:
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