Overview & Concept
Binary Search is an optimal divide-and-conquer search algorithm for sorted arrays. By comparing the search target with the middle element, it eliminates half of the remaining search space in each step, achieving guaranteed O(log n) logarithmic time complexity.
How It Works
Pre-condition: Requires array to be sorted in ascending order.
Midpoint Calculation: Computes mid = low + ⌊(high - low) / 2⌋ (safeguarding against integer overflow).
Three-Way Comparison: If A[mid] == target, returns mid; if A[mid] < target, discards left half; if A[mid] > target, discards right half.
Logarithmic Reduction: Search interval halves in each iteration until low > high.
Step-by-Step Execution
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(1) | O(log n) | O(log n) | O(1) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
procedure binarySearch(A, target):
low = 0; high = length(A) - 1
while low <= high:
mid = floor((low + high) / 2)
if A[mid] == target: return mid
else if A[mid] < target:
low = mid + 1 // eliminate left half
else:
high = mid - 1 // eliminate right half
return -1 // target not found- Search Interval Invariant: If target exists in array, it is strictly within A[low..high].
Advantages & Disadvantages
Key Advantages
- •Logarithmic O(log n) time: can search 1,000,000,000 elements in at most 30 comparisons.
- •O(1) auxiliary space in iterative implementation.
Trade-offs & Limitations
- •Requires pre-sorted array: sorting an unsorted array takes O(n log n).
- •Requires random access: inefficient on linked lists.
Real-World Applications
Database Index B-Tree Searching
Searching sorted keys inside B-Tree disk pages.
Git Bisect
Binary searching commit history to isolate the commit that introduced a regression.
Numeric Optimization & Root Finding
Bisection method solving continuous mathematical equations.
Decision Guide: When to Use
Ideal Scenarios
- ✓When searching sorted collections with random index access.
- ✓When performing repeated queries on static or infrequently mutated datasets.
Consider Alternatives When
- ✕When the dataset is unsorted and queried only once.
- ✕When data is stored in a linked list without O(1) random access.
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.