Mental model
Looking for a word in a printed dictionary, you do not start at page one. You open it near the middle, see whether your word comes before or after that page, and throw away the half that cannot contain it. Binary search is exactly that, done on an array that is sorted in ascending order.
It keeps a range of candidates, the only positions where the target can still be:
low: the first candidate.high: the last candidate (classic version) or one past it (first-occurrence version).mid: the middle of the range, the one element looked at in this iteration.
Comparing values[mid] with the target settles the fate of every element on one side at once.
If values[mid] < target, then because the array is sorted, everything at or left of mid is
smaller too, so low jumps to mid + 1. Otherwise high moves left. The lab fades every element
that has been ruled out, so you can watch the range collapse.
Sorted order is not a detail; it is the whole reason the method works. On unsorted input binary search does not fail loudly, it silently returns wrong answers. That is why the lab rejects unsorted input instead of sorting it behind your back.
The classic version
low = 0, high = n - 1
while low <= high:
mid = low + (high - low) / 2
if values[mid] == target: return mid
if values[mid] < target: low = mid + 1
else: high = mid - 1
return -1
Loop invariant. If the target is anywhere in the array, it is at an index in [low, high].
It holds at the start (the range is the whole array) and each update keeps it, because it only
discards positions whose values are known to be too small or too large. When low > high the
range is empty, so the target is not present and returning -1 is correct.
Termination. Each iteration either returns or makes the range strictly smaller: low grows
past mid or high drops below it. A range of n elements cannot shrink forever.
Why low + (high - low) / 2
(low + high) / 2 is mathematically the same, but in C#, Java and C++ the sum can exceed the
largest int when the array is huge, wrap around to a negative number and index outside the
array. This exact bug sat in the JDK's own Arrays.binarySearch for about nine years before it
was found in 2006. low + (high - low) / 2 never exceeds high. Python integers have arbitrary
precision, so the Python version keeps the simpler (low + high) // 2.
The C++ code uses std::ptrdiff_t (signed) indices on purpose: with high = size - 1, an empty
span needs high = -1, which an unsigned std::size_t would turn into a huge positive number.
Why it is logarithmic
Each iteration leaves at most half of the candidates: a range of r elements becomes at most
⌊r / 2⌋. Starting from n, after k iterations at most n / 2ᵏ candidates remain, and the loop
cannot run once that drops below one. So the number of iterations is at most
⌊log₂ n⌋ + 1
which is 4 for 10 elements, 7 for 64, 20 for a million and 31 for two billion. A linear scan needs up to n comparisons. The chart in the lab draws the range size before each iteration next to that bound; the 64 values, worst case preset hits it exactly.
| Time | Extra space | |
|---|---|---|
Best case (target at the first mid) |
O(1) | O(1) |
| Worst and average case | O(log n) | O(1) |
| Recursive version | O(log n) | O(log n) call stack |
The classic version evaluates up to two comparisons per iteration (==, then <), which the
Comparisons metric counts separately. The first-occurrence version does one per iteration plus
one at the end, so it often compares less even though it never stops early.
O(log n) assumes reaching values[mid] costs O(1), which is true for arrays. On a linked list the
comparisons are still logarithmic, but walking to the middle is linear, so the whole search is O(n).
Duplicates: any match or the first one
With duplicates the classic version returns some index of the target, whichever one a mid
lands on first. In [1, 3, 3, 3, 3, 3, 7, 9] it returns 3, not 1. That is a legitimate contract
(the built-ins below promise no more), but often you need the first or last copy, or the position
where a missing value would go.
The lower bound is the first index whose value is ≥ target. It uses a half-open range
[low, high) and never stops early:
low = 0, high = n
while low < high:
mid = low + (high - low) / 2
if values[mid] < target: low = mid + 1
else: high = mid # mid may be the answer; keep it
return low
The invariant is now: everything left of low is smaller than the target, and everything at or
right of high is ≥ the target. When low == high, that index is the lower bound. It may be n
(every value is smaller). The first occurrence is the lower bound if values[low] == target,
otherwise the target is absent. Compare the presets Duplicates: any match and Duplicates: first
match in the lab: same array, different contract, different result.
Two details make the half-open version safe. high = mid, not mid - 1, because mid itself may
be the answer. And mid is always strictly below high, so it is always a real index and the
range always shrinks.
Built-in binary search
| Language | Call | Not found | Duplicates |
|---|---|---|---|
| C# | Array.BinarySearch(a, x), List<T>.BinarySearch(x) |
negative number: the bitwise complement ~i of the index of the next larger element |
any matching index |
| Python | bisect.bisect_left(a, x) / bisect_right |
no "found" result: returns the insertion point; check a[i] == x yourself |
bisect_left gives the first position |
| Java | Arrays.binarySearch(a, x), Collections.binarySearch(list, x) |
-(insertion point) - 1 |
"no guarantee which one will be found" |
| C++ | std::binary_search (bool), std::lower_bound, std::upper_bound, std::equal_range |
lower_bound returns the insertion position |
lower_bound gives the first |
All of them assume sorted input and say the result is undefined (or unspecified) otherwise; none of
them checks. Python's bisect functions accept a key= function since Python 3.10. Java's
Collections.binarySearch on a large list without random access (such as LinkedList) walks the
list with an iterator: O(log n) comparisons but O(n) traversal, the caveat from the previous
section. C++ lower_bound likewise needs only forward iterators, and is linear in steps on them.
The teaching implementation
IndexOf / index_of is the classic version and FirstIndexOf / first_index_of the
lower-bound version, written the same way in all four languages so the lab can highlight the
matching lines in each. The listings below are the exact files the tests run: every language reads
one shared fixture file (found, missing, empty, single element, duplicates, extremes), where the
classic result for duplicates is a range of acceptable indices rather than one exact index. Each
language also compares its results with its built-in search on 2,000 random sorted arrays.
Common mistakes
- Searching unsorted data. The result is meaningless, not an error. Sort first (O(n log n)) or use a hash set if you only need membership.
- Mixing interval conventions.
while (low <= high)belongs withhigh = n - 1andhigh = mid - 1;while (low < high)withhigh = nandhigh = mid. Mixing them either skips the last candidate or loops forever on a two-element range. low = midinstead ofmid + 1. Whenhigh = low + 1,mid == low, so the range never shrinks and the loop never ends.- Overflowing the midpoint in fixed-width integer languages.
- Treating the built-in's negative result as an index. In C# and Java it encodes the
insertion point; decode it with
~ior-(i + 1).
Edge cases
- Empty array: the loop never runs; the result is -1 without any comparison.
- One element: one iteration.
- Target smaller than every element:
highkeeps moving left until it is -1 (classic); the lower bound is 0. - Target larger than every element:
lowends at n; the lower bound is n, one past the end. - All elements equal to the target: the classic version returns the middle one; the first-occurrence version returns 0.
Worked practice
1. How many iterations does the classic search take at most on 1,000 elements?
Answer
⌊log₂ 1000⌋ + 1 = 9 + 1 = 10 (2⁹ = 512 ≤ 1000 < 1024 = 2¹⁰).
2. In [2, 4, 4, 4, 9], what do the classic and first-occurrence versions return for 4?
Answer
Classic: the first mid is 2, and values[2] = 4, so it returns 2. First occurrence: the lower
bound is 1, and values[1] = 4, so it returns 1.
3. How do you find the last occurrence of a value?
Answer
Find the upper bound, the first index whose value is > target (change < to <= in the
lower-bound loop), then check the element just before it: if upper > 0 and
values[upper - 1] == target, the last occurrence is upper - 1. The number of copies is
upper - lower.
4. Why can the first-occurrence loop not stop as soon as it sees the target?
Answer
A match at mid proves only that the first occurrence is at mid or earlier. Elements left of
mid may also equal the target, so it keeps mid in the range (high = mid) and continues until
the range is empty.
Summary
- Binary search needs sorted input and random access; it rules out half the candidates per step.
- At most ⌊log₂ n⌋ + 1 iterations: O(log n) time, O(1) extra space iteratively.
- The loop invariant ("if present, the target is in the range") proves correctness.
- With duplicates, decide what you need: any match, the first (lower bound) or the last (upper bound).
- Built-ins encode "not found" differently: C#
~i, Java-(i + 1), Python and C++ return the insertion point directly.