Is a search algorithm that finds an element in a sorted array by repeatedly dividing the search area in half, and it’s time complexity is O(log n).
The implementation consists on:
- Initializing two pointers, to mark the start and end of the search area
- Using these pointers to calculate the middle index of the current search area
- Comparing the element in the middle with the target element
- Tweak the pointers based on the comparison result:
- Repeat steps 2-4 until the target is found
How the comparison works:
- If middle element is equal to the target, return the middle index
- If the middle element is less than the target, move the start pointer to
middle + 1 - If the middle element is greater than the target, move the end pointer to
middle - 1
This is called “binary” search because each comparison cuts the search area in half, making it highly efficient.
Here is a Python implementation of binary search:
def binary_search(arr: list[int], target: int) -> int:
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1TIP
Binary Search requires only two things: a sorted array and a comparable data type (not just integers). Array length (odd/even) doesn’t matter.