Binary Search is a divide-and-conquer searching algorithm for sorted arrays. By comparing the target against the middle element of the current interval, it eliminates half of the remaining candidates on every step, achieving logarithmic lookup time. Even across a billion sorted elements, it needs at most 30 comparisons, compared to a billion in the worst case for Linear Search.
Binary Search maintains two bounds, low and high, spanning the candidate window. At each step it computes mid = floor((low + high) / 2). If arr[mid] matches the target, it returns mid. If arr[mid] is smaller, the target can only lie in the right half (low = mid + 1); otherwise it narrows to the left half (high = mid − 1). When low crosses high, the candidate window is empty and the search returns −1.
low = 0, high = n - 1
while low <= high:
mid = floor((low + high) / 2)
if arr[mid] == target:
return mid
else if arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Control speed:
mid requires pointer traversal.Use Binary Search whenever your data is already sorted and supports fast random access (like arrays). Beyond array lookups, Binary Search generalizes to any monotonic predicate (known as Binary Search on Answer) to optimize thresholds in scheduling, capacity planning, and root finding. For uniformly distributed numeric keys on very large arrays.
Metric / Operation | Complexity | Description |
|---|---|---|
| Best Case | O(1) | When the middle element checked on the very first step equals the target. |
| Average Case | O(log n) | Each comparison eliminates half of the remaining search space. |
| Worst Case | O(log n) | When the target is at a boundary or absent after halving down to an empty window. |
| Space Complexity | O(1) | Iterative Binary Search uses constant memory, while recursive takes O(log n) stack space. |
Instead of returning immediately when arr[mid] == target, record mid as a candidate answer and keep narrowing: move high = mid - 1 to find the first occurrence (lower bound), or low = mid + 1 to find the last occurrence (upper bound).
Whenever an optimization problem has a monotonic feasibility check (every value above or below a threshold is valid), you can binary search directly over the numeric answer range [min, max] instead of an explicit array, finding the optimal threshold in O(log(max − min) · checkCost) time.
to join the discussion
Hand-picked resources to deepen your understanding
© 2025 See Algorithms. Code licensed under MIT, content under CC BY-NC 4.0