Junior — Middle
Explain the working principle of the binary search algorithm and its main stages.
sobes.tech AI
Answer from AI
The binary search algorithm is used to find an element in a sorted array. Its principle is based on repeatedly dividing the search area in half and comparing the target value with the middle element of the current range.
Main stages:
- Define the initial range — usually the entire array (left and right boundaries).
- Find the index of the middle element of the range.
- Compare the target value with the middle element:
- If they are equal, return the index of the found element.
- If the target is less, narrow the search to the left half (move the right boundary).
- If greater, narrow to the right half (move the left boundary).
- Repeat steps 2-3 until the range becomes empty.
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 # element not found