Linear Search vs Binary Search: O(n), O(log n) and bisect
Searching is the simplest place to see what a better algorithm buys you. Linear search looks at every item; binary search throws away half of the remaining items with each comparison. The idea of binary search is short, but writing it correctly takes care, so this post states the invariant that keeps it correct and the traps that break it. Examples use Python 3.10 or later and only the standard library.
Linear search: O(n) on any list
Linear search checks the items one by one until it finds the target or runs out:
def linear_search(items, target): # O(n), works on any list
for i, x in enumerate(items):
if x == target:
return i
return -1
print(linear_search([7, 3, 9, 3], 3), linear_search([7, 3, 9, 3], 5))
1 -1
It needs nothing from the data: no order, no hashing, not even random access. Its best case is O(1) (the target is first) and its worst case O(n) (the target is last or missing). For a present target in a random position it makes about n/2 comparisons on average, which is still O(n). Python's x in a_list and a_list.index(x) are linear searches.
Binary search: O(log n) on sorted input
If the list is sorted, one comparison with the middle item tells you which half the target must be in, and the other half can be discarded. Each step halves the range, so after k steps at most n / 2^k items remain, and the search ends after about log2 n steps: O(log n) time.
The requirement is real: on an unsorted list, binary search returns wrong answers without any error. And sorting first costs O(n log n), so for a single search on unsorted data a linear scan is cheaper. Binary search pays off when you sort once and search many times.
A correct iterative binary search
The version below keeps a closed range lo..hi of indices still in play. Everything rests on one sentence, the loop invariant: if the target is in the list, its index lies between lo and hi inclusive. It is true at the start (the whole list), each branch keeps it true (it only discards indices that cannot hold the target), and when lo > hi the range is empty, so the target is not there.
import math
def binary_search(a, target):
"""Return an index of target in sorted list a, or -1. Also return probes."""
lo, hi = 0, len(a) - 1
probes = 0
# Invariant: if target is in a, its index is in the range lo..hi.
while lo <= hi:
mid = lo + (hi - lo) // 2
probes += 1
if a[mid] == target:
return mid, probes
if a[mid] < target:
lo = mid + 1 # target, if present, is right of mid
else:
hi = mid - 1 # target, if present, is left of mid
return -1, probes # lo > hi: the range is empty
a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print(binary_search(a, 23), binary_search(a, 2), binary_search(a, 7))
n = 1_000_000
big = list(range(n))
worst = max(binary_search(big, t)[1] for t in range(-1, n + 1))
print("most probes for n = 1,000,000:", worst)
print("floor(log2(n)) + 1 =", math.floor(math.log2(n)) + 1)
(5, 3) (0, 3) (-1, 3)
most probes for n = 1,000,000: 20
floor(log2(n)) + 1 = 20
On a million items, no search needed more than 20 probes, matching floor(log2(1,000,000)) + 1 = 20. A linear search could need a million comparisons for the same list. This iterative version uses O(1) extra space; a recursive version uses O(log n) stack space for its calls.
Off-by-one traps
Most broken binary searches mix two conventions. Pick one and keep every line consistent with it.
- Closed range
lo..hi(as above): start withhi = len(a) - 1, loopwhile lo <= hi, and move tomid + 1ormid - 1. Writingwhile lo < hihere skips the last remaining candidate, so a one-item range is never checked. - Half-open range
lo..hi-1: start withhi = len(a), loopwhile lo < hi, and sethi = mid(notmid - 1) when going left, becausehiis already excluded. - Infinite loops: if a branch sets
lo = midwhilemidcan equallo, a two-item range never shrinks. Every branch must removemidor move a boundary past it. - Test the edges: an empty list, one item, the first item, the last item, a target smaller than everything and one larger than everything. The 1,000,000-item loop above checks every target from -1 to n.
The midpoint is written lo + (hi - lo) // 2 rather than (lo + hi) // 2. In languages with fixed-width integers, such as C or Java, lo + hi can overflow when both are large, producing a negative index. Python integers grow as needed and never overflow, so in Python both forms give the same answer; the safer form is shown because it is the habit to carry into other languages.
Python's bisect module
The standard library's bisect module implements binary search on sorted lists, and it answers a slightly different question: where would x go to keep the list sorted?
bisect_left(a, x)returns the first index whose item is at least x (the position of the first copy of x, if present).bisect_right(a, x)returns the first index whose item is greater than x (one past the last copy).
from bisect import bisect_left, bisect_right
a = [1, 3, 3, 3, 5, 8]
print(bisect_left(a, 3), bisect_right(a, 3)) # first 3, one past the last 3
print(bisect_right(a, 3) - bisect_left(a, 3)) # how many 3s
print(bisect_left(a, 4)) # where 4 would be inserted
def index_of_first(a, x):
i = bisect_left(a, x)
return i if i < len(a) and a[i] == x else -1
print(index_of_first(a, 3), index_of_first(a, 4), index_of_first(a, 9))
1 4
3
4
1 -1 -1
The difference of the two counts the copies of x in O(log n). bisect_left alone does not tell you whether x is present, so check the item at that index, as index_of_first does; forgetting the i < len(a) test raises IndexError when x is larger than everything. bisect.insort inserts while keeping order, but the insertion itself shifts items and costs O(n).
Binary search on the answer
Binary search works on more than lists. Whenever a yes/no condition is monotonic (false for all small x, then true for all larger x), you can binary search for the smallest x where it becomes true, as long as you can test the condition. Here the condition is x * x >= n, which finds the integer square root rounded up, checked against math.isqrt:
import math
def smallest_root_at_least(n):
"""Smallest integer x >= 0 with x * x >= n, by binary search on x."""
lo, hi = 0, n # the answer is somewhere in 0..n
while lo < hi: # invariant: the answer is in lo..hi
mid = (lo + hi) // 2
if mid * mid >= n: # condition holds: answer is mid or smaller
hi = mid
else: # condition fails: answer is above mid
lo = mid + 1
return lo
for n in [0, 1, 15, 16, 17, 10**12 + 1]:
x = smallest_root_at_least(n)
assert x == math.isqrt(n) + (math.isqrt(n) ** 2 != n)
print(n, x)
0 0
1 1
15 4
16 4
17 5
1000000000001 1000001
This uses the half-open style: the loop keeps the answer in lo..hi, sets hi = mid when the condition holds (mid might be the answer) and lo = mid + 1 when it fails. For n around 10^12 it takes about 40 tests instead of a million. The same template answers questions such as "the smallest capacity that ships everything within d days", where checking one capacity is easy but searching all of them is not.
The recurrence and the tools
Binary search does constant work and then recurses on half the input: T(n) = T(n/2) + O(1). In master theorem terms that is a = 1, b = 2, d = 0, and the Master Theorem Calculator returns Case 2, "Θ(log n)". The Algorithm Comparison Tool lists binary search as O(1) best case (the first probe hits), O(log n) average and worst, with O(1) space, which is the iterative version. At n = 1000 it gives binary search a count of 9.97 against linear search's 1,000 for the average case; those counts are log2 n and n, not measured times.
Check yourself
- What is the largest number of probes the closed-range version needs for 1,000 items? (floor(log2(1000)) + 1 = 10.)
- In the closed-range version, what goes wrong if you write
hi = midinstead ofhi = mid - 1? (Whenlo == hi == midand the target is smaller, the range never shrinks: an infinite loop.) - For
a = [1, 2, 2, 2, 3], what dobisect_left(a, 2)andbisect_right(a, 2)return? (1 and 4.)