AlgoViz

Binary search

easy 16 min

Binary search finds a value, a boundary or an insertion point in sorted data by checking the middle and discarding the half that cannot hold the answer.

Video lesson · Chapter 1 of 6

The guess that rules out a crowd

0:00 / 5:12

Classic binary search

1:10Reel

Binary search in one picture
Binary search in one picture

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

First and last position

1:12Reel

Search insert position

1:12Reel

Minimum in a rotated array

1:11Reel

Search in a rotated array

1:16Reel

Find a peak element

1:09Reel

Binary search on the answer

1:16Reel

Search a 2D matrix

1:05Reel

Binary search bugs

1:10Reel

When to use binary search

1:10Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Bound the range. Put left and right around every index that could still hold the answer

Understand it

Start here

What binary search is

Binary search finds a target in a sorted array without looking at most of it. It checks the middle element. If that is not the target, the order of the array says which half the target must be in, and the other half is thrown away. Every comparison removes half of the remaining candidates. It is the number guessing game: for a number from 1 to 100 you guess 50, hear "lower", and half the numbers are gone in one guess.

  • Bound

    left and right mark the range that may still hold the answer.

  • Probe

    Look at arr[mid], the middle of that range.

  • Halve

    Move left or right past mid. Half the range is gone.

  • Stop

    Found it, or the range is empty and the target is not there.

The picture

Halving: 16 values, found in 3 probes

Search for 23 in the 16 sorted values [2, 5, 8, 12, 16, 23, 38, 45, 56, 72, 91, 95, 100, 112, 120, 150]. Watch the live range shrink:

ProbeLive rangeSizemid → valueDecision
1indexes 0 to 15167 → 4523<4523 < 45: keep the left half
20 to 673 → 1223>1223 > 12: keep the right half
34 to 635 → 23found at index 5
worst case16 → 8 → 4 → 2 → 15 probes: ⌊log⁡216⌋+1\lfloor \log_2 16 \rfloor + 1
This target needed 3 probes. The worst case for 16 values is 5: four halvings to reach one candidate, plus one probe to check it. A linear scan could need 16.

The algorithm

Classic search on a closed interval

One loop of classic binary search

LIMP: Loop while the range is not empty, compute the Index of the middle, Match against the target, move a Pointer.
Python
def binary_search(arr, target):    left, right = 0, len(arr) - 1    while left <= right:        mid = left + (right - left) // 2        if arr[mid] == target:            return mid            # found        elif arr[mid] < target:            left = mid + 1        # search the right half        else:            right = mid - 1       # search the left half    return -1                     # not foundnums = [1, 3, 5, 7, 9, 11, 13]print(binary_search(nums, 7))    # 3: the very first midprint(binary_search(nums, 11))   # 5: two probesprint(binary_search(nums, 6))    # -1print(binary_search([], 4))      # -1: right = -1, the loop never runs
Closed interval [left, right]: both ends are candidates, so the loop runs while left <= right.
Edit and run it in your browser

Overflow

The overflow-safe midpoint

The obvious midpoint (left + right) // 2 has a famous bug. In languages with 32-bit integers (Java, C, C++) the sum can exceed the largest int even though both indexes fit, and it wraps to a negative number. This bug sat in the JDK's own binary search for about nine years before it was found in 2006.

Same value, no big sum

mid=⌊ℓ+r2⌋=ℓ+⌊r−ℓ2⌋,0≤r−ℓ<231\text{mid} = \left\lfloor \frac{\ell + r}{2} \right\rfloor = \ell + \left\lfloor \frac{r - \ell}{2} \right\rfloor, \qquad 0 \le r - \ell < 2^{31}
With ℓ=1.5×109\ell = 1.5 \times 10^9 and r=2×109r = 2 \times 10^9 the sum 3.5×1093.5 \times 10^9 is bigger than 231−1≈2.147×1092^{31} - 1 \approx 2.147 \times 10^9. The difference 5×1085 \times 10^8 always fits.
LanguageSafe midpoint
Pythonleft + (right - left) // 2 (ints never overflow, but NumPy int32 does)
Javaleft + (right - left) / 2 or (left + right) >>> 1
C / C++left + (right - left) / 2
JavaScriptleft + ((right - left) >> 1) or Math.floor((left + right) / 2)
Both forms floor the result, so they pick the left of the two middles when the range has even length.

Correctness

Loop invariants

Every correct binary search keeps one promise, its loop invariant, true before each loop. Write the invariant first and the pointer updates follow from it. For the classic search: if the target is in the array at all, it is inside arr[left..right].

Two invariants, two templates

target∈a  ⇒  target∈a[ℓ..r]⏟closed: exact matcha[i]<t    ∀i<ℓ,a[i]≥t    ∀i≥r⏟half-open: lower bound\underbrace{\text{target} \in a \;\Rightarrow\; \text{target} \in a[\ell..r]}_{\text{closed: exact match}} \qquad \underbrace{a[i] < t \;\; \forall i < \ell, \quad a[i] \ge t \;\; \forall i \ge r}_{\text{half-open: lower bound}}
Closed: dropping mid with ℓ=mid+1\ell = \text{mid} + 1 or r=mid−1r = \text{mid} - 1 is safe because mid was just checked. Half-open: when ℓ=r\ell = r the two zones meet, and ℓ\ell is the first index with a[i]≥ta[i] \ge t.

Initialise, maintain, terminate

Two things must be true each loop: the invariant survives, and the range gets strictly smaller. Break the second and the loop never ends.

Off by one

Closed versus half-open intervals

TemplateStartLoopShrinkReturns
Exact matchright = len - 1left <= rightmid + 1 / mid - 1mid or -1
First / last occurrenceright = len - 1left <= rightsave mid, then mid - 1 or mid + 1saved result
Search insertright = len - 1left <= rightmid + 1 / mid - 1left
Lower / upper boundright = lenleft < rightright = mid / left = mid + 1left (may be len)
Pick one row and keep it consistent. Most off-by-one bugs come from mixing the start of one row with the loop of another.

Do

  • Decide closed [ℓ,r][\ell, r] or half-open [ℓ,r)[\ell, r) before writing a line.
  • Use mid ± 1 when mid has been ruled out; right = mid when mid may be the answer.
  • Trace a 1-element and a 2-element array by hand.
  • Test target below all, above all, missing in the middle, and duplicated.

Don't

  • Pair right = len(arr) with while left <= right: arr[len] raises IndexError.
  • Use while left < right with right = len - 1 in the exact-match template: it skips the last candidate.
  • Set left = mid with a floor midpoint.
  • Forget that a bound can return len(arr) when every value is smaller.

Variants

Boundaries: first, last, lower and upper bound

With duplicates, classic search returns any matching copy. Boundary searches do not stop at a match; they keep shrinking toward one side. On [1, 2, 4, 4, 4, 6, 8]: the first 4 is at index 2, the last at 4, lower_bound(4) = 2 (first value ≥4\ge 4) and upper_bound(4) = 5 (first value >4> 4).

Which variation do I need?

Peaks and rotated arrays are covered below. They use the same loop with a different test.
Python
from bisect import bisect_left, bisect_righta = [1, 2, 4, 4, 4, 6, 8]lo, hi = bisect_left(a, 4), bisect_right(a, 4)print(lo, hi, hi - lo)        # 2 5 3: three 4s at indexes 2..4print(bisect_left(a, 5))      # 5: where 5 would be insertedprint(bisect_left(a, 9))      # 7: len(a), every value is smaller# first and last occurrence from the boundsfirst = lo if lo < len(a) and a[lo] == 4 else -1last = hi - 1 if first != -1 else -1print(first, last)            # 2 4
Python ships the bounds as bisect_left and bisect_right. Counting a value is upper minus lower.
Edit and run it in your browser

Complexity

Deriving O(log n)

After kk comparisons at most n/2kn / 2^k candidates remain. The search must stop once one candidate is left, so we solve for kk. This is the definition of a logarithm: how many times you can halve nn before reaching 1.

How many halvings?

n2k=1  ⟹  2k=n  ⟹  k=log⁡2n,Cworst(n)=⌊log⁡2n⌋+1\frac{n}{2^k} = 1 \;\Longrightarrow\; 2^k = n \;\Longrightarrow\; k = \log_2 n, \qquad C_{\text{worst}}(n) = \lfloor \log_2 n \rfloor + 1
The +1+1 is the final probe of the last candidate. For n=7n = 7: 3. For n=16n = 16: 5. For n=106n = 10^6: 20.

The recurrence

T(n)=T ⁣(n2)+O(1)=T ⁣(n4)+2c=⋯=T(1)+clog⁡2n=O(log⁡n)T(n) = T\!\left(\tfrac{n}{2}\right) + O(1) = T\!\left(\tfrac{n}{4}\right) + 2c = \dots = T(1) + c \log_2 n = O(\log n)
One comparison of constant cost, then half the problem. Unrolled, there are log⁡2n\log_2 n levels. Space is O(1)O(1) iteratively; a recursive version uses O(log⁡n)O(\log n) stack frames.
nBinary search (worst)Linear search (worst)Linear search (average)
16516about 8
1,000101,000about 500
1,000,000201,000,000about 500,000
1,000,000,000301,000,000,000about 500,000,000
Best case is O(1)O(1): the target is the first mid. Average and worst are both Θ(log⁡n)\Theta(\log n). Space O(1)O(1): just left, right and mid.

Generalisation

Binary search on the answer space

Binary search needs a monotonic test, not an array. If a yes or no question ok(x) flips from no to yes exactly once as xx grows, then the smallest xx with ok(x) is a lower bound you can binary search, over a range of numbers. Typical wording: minimise the maximum, maximise the minimum, smallest capacity, fewest days.

Search on the answer

Cost is O(log⁡(hi−lo))O(\log(\text{hi} - \text{lo})) calls to ok. If ok scans the input in O(n)O(n), the total is O(nlog⁡R)O(n \log R).
Python
def days_needed(weights, cap):    days, load = 1, 0    for w in weights:        if load + w > cap:            days, load = days + 1, 0        load += w    return daysdef min_capacity(weights, d):    lo, hi = max(weights), sum(weights)    while lo < hi:        mid = lo + (hi - lo) // 2        if days_needed(weights, mid) <= d:            hi = mid          # feasible: try smaller        else:            lo = mid + 1      # infeasible: go bigger    return loprint(min_capacity([2, 4, 1, 3], 2))           # 6print(min_capacity([1, 2, 3, 4, 5, 6, 7], 3))  # 11
Smallest truck capacity that ships packages in order within d days.
Edit and run it in your browser

Beyond sorted arrays

Rotated arrays and peaks

  • Rotated sorted array

    [4, 5, 6, 7, 0, 1, 2] is sorted, then rotated. At any mid, one half is still sorted. Check if the target lies inside that sorted half; if not, it is in the other.

  • Peak element

    If arr[mid] > arr[mid + 1], a peak is at mid or to its left; otherwise it is to the right. The slope tells you which half to keep. Loop while left < right.

  • Minimum of a rotated array

    Compare arr[mid] with arr[right]. Bigger means the drop is to the right: left = mid + 1; otherwise right = mid.

  • Sorted matrix

    A matrix sorted row by row, each row starting after the last ended, is one sorted list of m⋅nm \cdot n cells: index kk is row k//nk // n, column k%nk \% n.

Search in a rotated sorted array

Each check uses the sorted half, where a range test is trustworthy. Still O(log⁡n)O(\log n) when values are distinct.
Python
def search_rotated(arr, target):    left, right = 0, len(arr) - 1    while left <= right:        mid = left + (right - left) // 2        if arr[mid] == target:            return mid        if arr[left] <= arr[mid]:                 # left half is sorted            if arr[left] <= target < arr[mid]:                right = mid - 1            else:                left = mid + 1        else:                                     # right half is sorted            if arr[mid] < target <= arr[right]:                left = mid + 1            else:                right = mid - 1    return -1def find_peak(arr):    left, right = 0, len(arr) - 1    while left < right:        mid = left + (right - left) // 2        if arr[mid] > arr[mid + 1]:            right = mid        # peak is at mid or to the left        else:            left = mid + 1     # peak is to the right    return leftprint(search_rotated([4, 5, 6, 7, 0, 1, 2], 0))   # 4print(search_rotated([4, 5, 6, 7, 0, 1, 2], 3))   # -1print(search_rotated([6, 7, 1, 2, 3, 4, 5], 6))   # 0print(find_peak([1, 2, 3, 1]))                    # 2print(find_peak([1, 2, 1, 3, 5, 6, 4]))           # 5 (index 1 is also a peak)
Both tricks keep the binary search loop and change only the test.
Edit and run it in your browser

Pattern spotting

When to reach for it

Use binary search when

  • The data is sorted, or can be sorted once and then searched many times.
  • You need a value, a boundary, a count or an insertion point.
  • A yes or no condition is monotonic: no, no, ..., yes, yes.
  • The structure has random access, so arr[mid] is O(1)O(1).
  • O(n)O(n) is too slow for the input size or the number of queries.

Skip it when

  • The data is unsorted and you search once: sorting costs O(nlog⁡n)O(n \log n), a scan O(n)O(n).
  • It is a linked list: reaching the middle is O(n)O(n).
  • The data changes constantly: keeping an array sorted costs O(n)O(n) per insert. Use a balanced tree.
  • The array is tiny: a linear scan is simpler and just as fast.
Binary searchLinear search
TimeO(log⁡n)O(\log n)O(n)O(n)
SpaceO(1)O(1)O(1)O(1)
Needs sorted dataYesNo
1 million valuesat most 20 comparisonsabout 500,000 on average
Works on linked listsNot efficientlyYes
Best useLarge sorted data, many queriesSmall or unsorted data, one query

Recap

Key takeaways

Key points

  • Binary search probes the middle and discards the half that cannot hold the answer: at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 comparisons, O(log⁡n)O(\log n) time, O(1)O(1) space.
  • It needs sorted data or, more generally, a monotonic yes or no test.
  • Use mid = left + (right - left) // 2; (left + right) // 2 overflows in fixed-width languages.
  • Closed [ℓ,r][\ell, r]: while left <= right, move to mid ± 1. Half-open [ℓ,r)[\ell, r): while left < right, right = mid, return left.
  • First or last occurrence: on a match save the index and keep going left or right. Count = upper_bound - lower_bound.
  • Search on the answer: binary search a number range with a feasibility check, O(nlog⁡R)O(n \log R).
  • Every loop must keep its invariant and shrink the range; left = mid with a floor midpoint is the classic infinite loop.

Sources