Binary Search in Data Structure
Binary Search is a searching algorithm that finds the position of a target value within a sorted array by repeatedly dividing the search range in half.
Algorithm Steps
- Compare the target with the middle element of the array.
- If they match, the search is complete.
- If the target is smaller, repeat the search on the left half.
- If the target is larger, repeat the search on the right half.
- Repeat until the target is found or the search range is empty.
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
def binary_search_recursive(arr, target, low, high):
if low > high:
return -1
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, high)
else:
return binary_search_recursive(arr, target, low, mid - 1)
Complexity
| Case | Time | Space (iterative) |
|---|---|---|
| Best | O(1) | O(1) |
| Average/Worst | O(log n) | O(1) |
Applications
- Searching in sorted databases and indexes.
- Finding the boundary in problems like 'first/last occurrence' or 'search in rotated sorted array'.
- Used in library functions like Python's
bisectmodule.
Tracing Binary Search on a Real Array
Take the sorted array [3, 8, 15, 21, 34, 42, 57, 66] and search for 42. Indexes run from 0 to 7.
| Step | low | high | mid | arr[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 7 | 3 | 21 | 42 is larger, so low becomes 4 |
| 2 | 4 | 7 | 5 | 42 | Match, return index 5 |
Only two comparisons were needed for eight elements. Now search for 40: mid 3 holds 21, so low moves to 4; mid 5 holds 42, so high drops to 4; mid 4 holds 34, so low moves to 5. At that point low is greater than high and the function returns -1. Watching low and high cross each other is how the algorithm knows a value is absent.
Finding the First Occurrence (Lower Bound)
When the array contains duplicates, the plain version returns whichever matching index it hits first, not necessarily the leftmost one. Many problems need the leftmost position, so the trick is to record the match and keep searching to the left.
def first_occurrence(arr, target):
low, high = 0, len(arr) - 1
answer = -1
while low <= high:
mid = low + (high - low) // 2
if arr[mid] == target:
answer = mid # remember it, keep looking left
high = mid - 1
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return answer
print(first_occurrence([1, 2, 2, 2, 5], 2)) # 1
Swap high = mid - 1 for low = mid + 1 inside the match branch and you get the last occurrence instead. Last index minus first index plus one gives the number of copies of a value, still in logarithmic time.
Python ships this logic ready-made: bisect.bisect_left(arr, x) returns the insertion point before any equal values, and bisect.bisect_right(arr, x) returns the point after them.
Bugs That Quietly Break Binary Search
- Unsorted input. You get a wrong answer, not an error. Sort the data first or pick a different method.
- Mixed range conventions. Using
low < highwhilehighstarts atlen(arr) - 1skips the final candidate. Choose either a closed range [low, high] or a half-open range [low, high) and keep every line consistent with it. - Ranges that never shrink. Writing
low = midinstead oflow = mid + 1can loop forever once two elements remain. - Overflow in C, C++ and Java.
(low + high) / 2can exceed the integer limit on huge arrays.low + (high - low) / 2avoids that. Python integers do not overflow, but the safer form is a good habit to carry across languages.
Choosing Binary Search Over Other Lookups
It pays off when the data is already sorted, or when you will search the same data many times. For a single lookup in unsorted data, a linear scan is cheaper than sorting first. For plain "is it present?" checks, a hash set usually answers faster on average. Binary search is the better tool when you also need ordering answers such as the nearest value, a range of values, or the smallest element greater than x.
The same idea works on answers rather than indexes. If a yes/no condition switches from false to true exactly once across a range, for example "can all packages ship within D days at capacity C?", you can binary search over C to find the minimum value that works.
- Confirm the input is sorted.
- Fix one range convention before writing code.
- Check that every branch shrinks the range.
- Test an empty array, a single element, and targets below or above every value.