One-Line Definition
Binary search repeatedly narrows the search interval over a sorted sequence or a search space with a monotonic truth value, typically requiring O(log n) comparisons per query.
Why It Matters
- It is the canonical algorithm, underlying B-tree indexes and Git's
git bisect(locating the commit that introduced a bug via binary search). - Binary search on the answer: Whenever the predicate "is this candidate answer feasible?" is monotonic, you can binary-search the answer space directly—for example, finding the maximum feasible batch size or a minimum learning-rate threshold.
Operating Boundaries
Locating an insertion point takes O(log n), but inserting into a Python list still takes O(n) due to element shifting. In practice, training quality is rarely monotonic with respect to learning rate, and GPU memory feasibility is affected by concurrency and allocator fragmentation—always verify the monotonicity assumption before binary-searching an answer space.
How It Works / Diagram
Each step halves the search interval. After steps, elements remain, terminating when the count drops below 1:
Python standard library bisect: https://docs.python.org/3/library/bisect.html
Runnable Example
Hand-written binary search with step counting, bisect for insertion indices and grade bucketing, binary search on the answer for maximum batch size under a VRAM budget, and the failure mode of running binary search on an unsorted list (Python 3.15.0 first-draft run log):
# File: examples/21_binary_search.py
# Binary search: discard half of a sorted sequence at each step, O(log n)
import bisect
def binary_search(a, target):
lo, hi, steps = 0, len(a) - 1, 0
while lo <= hi:
steps += 1
mid = (lo + hi) // 2
if a[mid] == target: return mid, steps
if a[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1, steps
a = list(range(0, 2_000_000, 2)) # 1,000,000 even numbers
for t in [0, 777_778, 1_999_998, 3]:
print(f"Find {t:>9}: index {binary_search(a, t)[0]:>7}, took {binary_search(a, t)[1]} steps")
print("log2(1,000,000) ≈ 20 -> at most ~20 steps")
# Standard library bisect: find insertion point; maintain sorted order
scores = [60, 70, 80, 90]
print("Insertion index for 85:", bisect.bisect_left(scores, 85))
grades = "FDCBA"
print("Grade buckets:", [grades[bisect.bisect_right(scores, s)] for s in [55, 60, 75, 99]])
# Binary search on the answer: monotonic predicate -> find max feasible batch size
def fits_in_memory(batch): # Assumption: VRAM usage grows monotonically with batch
return 1.2 + 0.37 * batch <= 24.0 # GB
lo, hi = 1, 1024
while lo < hi:
mid = (lo + hi + 1) // 2
if fits_in_memory(mid): lo = mid
else: hi = mid - 1
print("Max batch size within 24GB:", lo)
# Common mistake: binary search on unsorted data
print("Binary search for 1 on unsorted [5, 1, 3, 9, 2]:", binary_search([5, 1, 3, 9, 2], 1), "<- returns -1 even though 1 is present")
First-draft recorded output:
Find 0: index 0, took 19 steps
Find 777778: index 388889, took 20 steps
Find 1999998: index 999999, took 20 steps
Find 3: index -1, took 20 steps
log2(1,000,000) ≈ 20 -> at most ~20 steps
Insertion index for 85: 3
Grade buckets: ['F', 'D', 'C', 'A']
Max batch size within 24GB: 61
Binary search for 1 on unsorted [5, 1, 3, 9, 2]: (-1, 2) <- returns -1 even though 1 is present
- Searching across 1,000,000 elements takes at most 20 steps, matching .
- Final line: binary search on an unsorted list returns -1 even though 1 is present—sorted order is a strict precondition.
- The VRAM model in the batch size example is a synthetic linear function used solely to illustrate monotonic feasibility plus binary search.
Common Pitfalls
- Mismatched boundary updates causing infinite loops or missed elements: Pair
while lo <= hiwithhi = mid - 1, or pairwhile lo < hiwithhi = mid. Never mix the two conventions. - Running binary search on unsorted data: It silently returns wrong results without raising an error (as shown in the example).
- Assuming
(lo+hi)//2overflows in Python: Python integers have arbitrary precision, though in C or Java you should writelo + (hi - lo) // 2. - Needing the first or last occurrence among duplicates: Use
bisect_leftorbisect_rightrather than a basic equality check.
Connection to AI Development
- Probing max batch size or context length: When "runs without OOM" behaves monotonically, binary search quickly narrows down the limit (real GPU memory is also affected by fragmentation and concurrency, so treat results as a reference estimate).
- Coarse hyperparameter search: Binary-searching learning rates or decision thresholds on a logarithmic scale (provided the metric is monotonic with respect to the parameter).
- Quantiles and thresholding: Using
bisecton sorted scores to compute percentiles or slice retrieved candidates by threshold. - Using
git bisectto isolate the commit that caused a model regression: https://git-scm.com/docs/git-bisect
Further Reading
- Python
bisectdocumentation: https://docs.python.org/3/library/bisect.html - Wikipedia: Binary search https://en.wikipedia.org/wiki/Binary_search
git bisectdocumentation: https://git-scm.com/docs/git-bisect
Comprehension Check
If you use insort, does maintaining a sorted Python list take O(log n) per insertion?
Reference answer: No. Binary search finds the insertion position in O(log n), but shifting the subsequent list elements still takes O(n) in the worst case.
Verification & Reproduction
Verification date: 2026-10-14. Example status: passed. Run log: 21_binary_search.py.
Companion Code & Verification Materials