Kodewick
Start learning →
Binary search37 / 52

Binary search

Lesson 37 of 52 · Part 7 · Searching · about 16 minutes

Binary search finds a value in a sorted list by throwing away half the range with each look, O(log n): 100,000 items need at most 17 looks; with the half-open range [lo, hi) the loop runs while lo < hi.

A sorted list holds 100,000 order numbers and you need to know whether one of them is there. x in a compares from the front, one by one: up to 100,000 looks. Binary search throws away half with every look: 17 looks at most. Chapter 0 showed why it is O(log n); this chapter is about searching, and it starts by writing binary search correctly. It is only about ten lines, but < or <=, mid or mid + 1: get one character wrong and it misses numbers, or never stops.

Count the looks

Linear search compares from the first to the last and needs no order. Binary search needs the list sorted from small to large: look at the middle one; if it is smaller than what you want, the answer can only be in the right half; if it is bigger, only in the left half. Both versions with a counter, finding the last number and then a number that isn't there:

main.py
1def linear(a, x):2    looks = 03    for i in range(len(a)):4        looks += 15        if a[i] == x:6            return i, looks7    return -1, looks8 9def binary(a, x):10    looks = 011    lo, hi = 0, len(a)12    while lo < hi:13        mid = (lo + hi) // 214        looks += 115        if a[mid] == x:16            return mid, looks17        if a[mid] < x:18            lo = mid + 119        else:20            hi = mid21    return -1, looks22 23for n in [10, 1000, 100000]:24    a = list(range(0, 2 * n, 2))          # 0 2 4 …, sorted25    print("n =", n, "linear:", linear(a, a[-1])[1], "looks",26          "binary:", binary(a, a[-1])[1], "looks, missing one:", binary(a, -1)[1], "looks")
Output
n = 10 linear: 10 looks binary: 3 looks, missing one: 4 looks
n = 1000 linear: 1000 looks binary: 9 looks, missing one: 10 looks
n = 100000 linear: 100000 looks binary: 16 looks, missing one: 17 looks

n grew 10,000 times and linear search looks 10,000 times more; binary search only went from 4 looks to 17, and its worst case is exactly n.bit_length(). The price: the list must be sorted first, and you must be able to reach the middle one by its index directly. A list can, a linked list can't.

Choose one

9 elements, each as likely to be looked for as any other. On average, how many comparisons does a successful sequential search take (ASL)?

Choose one

The data is in a sorted singly linked list. Why not use binary search?

Choose one

1,000,000 sorted numbers. How many looks does binary search need at most?

Half-open: [lo, hi)

The safest way to write binary search is to fix one sentence first and make every line keep it true: if the number is there, it is in a[lo:hi]. This uses the same half-open range as slices: lo is in, hi is not.

  • At the start the whole list is possible: lo, hi = 0, len(a). hi points just past the last one, like a[0:len(a)].
  • Go on while the range holds something: while lo < hi. When lo == hi the range is empty.
  • a[mid] < x: mid and everything left of it are too small, lo = mid + 1.
  • a[mid] > x: mid and everything right of it are too big, hi = mid. hi is already left out, so writing mid leaves exactly mid out.
a (x = 23; the dashed place at the end is index 8, which is len(a))2581216233845012345678↑lo↑hi
1lo, hi = 0, len(a)2while lo < hi:3    mid = (lo + hi) // 24    if a[mid] == x:5        return mid6    if a[mid] < x:7        lo = mid + 18    else:9        hi = mid10return -1

Finding 23 among 8 numbers: the range [lo, hi) loses half each time, the box hi points at is not in the range, 3 looks

Look for a number that isn't there and the range shrinks until it is empty. It stops when lo == hi, and where lo stops is useful: it is exactly where x would be inserted. Next lesson's bisect is built on that.

a (x = 10)2581216233845012345678↑lo↑hi
1lo, hi = 0, len(a)2while lo < hi:3    mid = (lo + hi) // 24    if a[mid] == x:5        return mid6    if a[mid] < x:7        lo = mid + 18    else:9        hi = mid10return -1

Finding 10: the range shrinks to nothing, not found; lo stops at 3, exactly where 10 belongs (between 8 and 12)
main.py
1def binary_search(a, x):2    lo, hi = 0, len(a)            # if it is there, it is in a[lo:hi]3    while lo < hi:4        mid = (lo + hi) // 25        if a[mid] == x:6            return mid7        if a[mid] < x:8            lo = mid + 1          # mid and everything left are too small9        else:10            hi = mid              # mid and everything right are too big11    return -112 13a = [2, 5, 8, 12, 16, 23, 38, 45]14print([binary_search(a, x) for x in a])15print(binary_search(a, 10), binary_search(a, 1), binary_search(a, 50))16print(binary_search([], 7), binary_search([7], 7))
Output
[0, 1, 2, 3, 4, 5, 6, 7]
-1 -1 -1
-1 0

Always test it like this when you've written one: look for every element, then for a number below the smallest, one in a gap, and one above the largest, and finally an empty list and a list of one. Binary search bugs hide almost entirely at the two ends and in the moment when "only one or two are left".

Choose one

In 2 5 8 12 16 23 38 45, using the half-open version (lo, hi = 0, len(a)) to find 45, which indices are looked at, in order?

Fill inTap one to fill a blank; tap a blank to take it back

In the half-open binary search, what should hi become when a[mid] > x? Pick one so that the program prints 4 0 8 -1.

1def find(a, x):2    lo, hi = 0, len(a)3    while lo < hi:4        mid = (lo + hi) // 25        if a[mid] == x:6            return mid7        if a[mid] < x:8            lo = mid + 19        else:10            hi = 11    return -112 13a = [3, 8, 15, 23, 42, 57, 61, 79, 88]14print(find(a, 42), find(a, 3), find(a, 88), find(a, 50))
Exercise 1

Write a half-open binary search

Complete search(a, x): a is sorted from small to large; return the index if found, -1 if not. Use the half-open range [lo, hi).

It should print
[0, 1, 2, 3, 4, 5]
-1 -1 -1 -1
exercise1.py
1def search(a, x):2    lo, hi = 0, len(a)3    # while lo < hi: look at a[mid]; equal: return it; smaller: lo = mid + 1; bigger: hi = mid4    return -15 6a = [3, 7, 11, 15, 19, 24]7print([search(a, x) for x in a])8print(search(a, 1), search(a, 13), search(a, 30), search([], 5))
Output
Press Run or Ctrl+Enter

Almost right: three real bugs

Guess first. The version in this question mixes the start of the closed range (hi = len(a) - 1) with the loop of the half-open one (lo < hi, hi = mid):

Guess the outputA wrong guess is fine

Look for every number in a. What does it print?

1def find(a, x):2    lo, hi = 0, len(a) - 13    while lo < hi:4        mid = (lo + hi) // 25        if a[mid] == x:6            return mid7        if a[mid] < x:8            lo = mid + 19        else:10            hi = mid11    return -112 13a = [1, 3, 5, 7]14print([find(a, x) for x in a])

Now run all three common mistakes for real. The first one, lo = mid, hangs, so it has a counter: on round 21 it reports lo and hi at that moment:

main.py
1def lo_is_mid(a, x):                  # wrong: lo = mid2    lo, hi = 0, len(a)3    rounds = 04    while lo < hi:5        rounds += 16        if rounds > 20:7            return "stuck: lo = %d, hi = %d" % (lo, hi)8        mid = (lo + hi) // 29        if a[mid] == x:10            return mid11        if a[mid] < x:12            lo = mid13        else:14            hi = mid15    return -116 17def mixed(a, x):                      # wrong: hi = len(a) - 1, but lo < hi18    lo, hi = 0, len(a) - 119    while lo < hi:20        mid = (lo + hi) // 221        if a[mid] == x:22            return mid23        if a[mid] < x:24            lo = mid + 125        else:26            hi = mid27    return -128 29def minus_one(a, x):                  # wrong: half-open, but hi = mid - 130    lo, hi = 0, len(a)31    while lo < hi:32        mid = (lo + hi) // 233        if a[mid] == x:34            return mid35        if a[mid] < x:36            lo = mid + 137        else:38            hi = mid - 139    return -140 41a = [2, 5, 8, 12, 16, 23, 38, 45]42print(lo_is_mid(a, 23), lo_is_mid(a, 50))43for f in [mixed, minus_one]:44    missed = [x for x in a if f(a, x) == -1]45    print(f.__name__, "can't find:", missed)
Output
5 stuck: lo = 7, hi = 8
mixed can't find: [45]
minus_one can't find: [2, 12, 23]
  • lo = mid: every number that is there is found, but look for one that isn't and it hangs. With two left, lo = 7 and hi = 8, mid = (7 + 8) // 2 = 7, equal to lo again, and the range doesn't change at all.
  • mixed: misses the last element, the one you just guessed.
  • minus_one: hi = mid - 1 in a half-open range throws one too many away. Looking for 12, mid = 4, 16 > 12, hi becomes 3, but hi means "not included", so the 12 at index 3 is gone. It misses 3 of the 8 numbers.
a (x = 50, which isn't there)2581216233845012345678↑lo↑hi
1lo, hi = 0, len(a)2while lo < hi:3    mid = (lo + hi) // 24    if a[mid] == x:5        return mid6    if a[mid] < x:7        lo = mid8    else:9        hi = mid

The lo = mid version looking for 50: with two left mid equals lo, lo = mid changes nothing, and the loop never ends

There is only one rule: every round, the range must get smaller. In a half-open range mid always satisfies lo ≤ mid < hi, so lo = mid + 1 and hi = mid always shrink it; lo = mid can't shrink it when mid == lo.

Change it

This is the find you guessed at the start of this stage: it starts with the closed range's len(a) - 1, but the loop is half-open. Change only the green box so that 1, 3, 5 and 7 are all found.

1def find(a, x):2    lo, hi = 0, 3    while lo < hi:4        mid = (lo + hi) // 25        if a[mid] == x:6            return mid7        if a[mid] < x:8            lo = mid + 19        else:10            hi = mid11    return -112 13a = [1, 3, 5, 7]14print([find(a, x) for x in a], find(a, 4))
Should print
[0, 1, 2, 3] -1

Computing mid: Python doesn't overflow

In C and Java you will see mid = lo + (hi - lo) / 2 instead of (lo + hi) / 2. The reason: their int has only 32 bits, about 2.1 billion at most. With an array of 1.5 billion elements, lo + hi goes past that and wraps around to a negative number, and the index is wrong. Java's standard Arrays.binarySearch carried this bug for years before it was fixed in 2006.

Python's int has no upper limit, so (lo + hi) // 2 is always right. Here is what a 32-bit int would do, simulated with a modulo:

main.py
1def as_int32(x):                     # simulate C / Java's 32-bit int: wrap around when out of range2    return (x + 2**31) % 2**32 - 2**313 4lo, hi = 1_500_000_000, 2_000_000_0005print("Python's lo + hi:", lo + hi, "mid =", (lo + hi) // 2)6s = as_int32(lo + hi)7print("32-bit int lo + hi:", s, "mid =", s // 2)8print("lo + (hi - lo) // 2:", lo + (hi - lo) // 2)
Output
Python's lo + hi: 3500000000 mid = 1750000000
32-bit int lo + hi: -794967296 mid = -397483648
lo + (hi - lo) // 2: 1750000000

hi - lo is never more than the array's length, and adding it to lo never goes past hi, so it never overflows. In Python both forms give the same result, so either is fine; in an interview, writing lo + (hi - lo) // 2 and saying in passing why earns a point.

Closed [lo, hi]Half-open [lo, hi)
Starthi = len(a) - 1hi = len(a)
Loop conditionlo <= hilo < hi
a[mid] < xlo = mid + 1lo = mid + 1
a[mid] > xhi = mid - 1hi = mid
Stops (not found) atlo == hi + 1lo == hi

Both are right; mixing them is wrong. Half-open is the same habit as Python's slices and range, and next lesson's lower bound and bisect are written this way too.

In interviews: before writing a binary search, say "I'm using half-open, the answer is in a[lo:hi]", then write the code; afterwards walk through an empty list, one element, the first, the last, and a missing one. Asked "why write mid like that?", tell the 32-bit overflow story and Java's bug fix.

Choose one

In C or Java, an int tops out at about 2.1 billion. With lo = 1.5 billion and hi = 2 billion, which formula gives the right mid?

Choose one

You switch to a closed range [lo, hi]. Which set of lines is right?

How you write it at work

You don't have to write it every time: the standard library's bisect.bisect_left(a, x) is a ready-made half-open binary search. It returns where x would be inserted (exactly where lo stopped in the half-open stage). To check whether x is there, look once at that position:

main.py
1from bisect import bisect_left2 3def index_of(a, x):                  # a must be sorted4    i = bisect_left(a, x)5    if i < len(a) and a[i] == x:6        return i7    return -18 9a = [2, 5, 8, 12, 16, 23, 38, 45]10print(index_of(a, 23), index_of(a, 10), index_of(a, 50))11print(a.index(23), 23 in a)          # both walk from the front: O(n)12ids = set(a)13print(23 in ids)                     # only "is it there?": a set is O(1) on average
Output
5 -1 -1
5 True
True
CodeNeedsTime
x in a, a.index(x)nothingO(n): it doesn't know a is sorted
bisect_left(a, x) + one looka already sortedO(log n)
x in s (s a set)hashable elementsO(1) on average, but no order
sorted(a) first, then binary searchnothingsorting O(n log n), then O(log n) each

If you only ask "is it there?", a set is fastest. Binary search is for questions about order: "the first one ≥ 60", "how many between 80 and 90". Unsorted data searched once or twice: just use x in a. Sorting first for one search, O(n log n), is slower than O(n).

Exercise 2

Scores sorted high to low

A score list is sorted from high to low. search_desc(a, x) was written as if it were low to high, and many scores can't be found. Fix it: return the index if found, -1 if not.

It should print
[0, 1, 2, 3, 4, 5]
-1 -1 -1
exercise2.py
1def search_desc(a, x):2    lo, hi = 0, len(a)3    while lo < hi:4        mid = (lo + hi) // 25        if a[mid] == x:6            return mid7        if a[mid] < x:8            lo = mid + 19        else:10            hi = mid11    return -112 13a = [98, 91, 85, 77, 60, 42]14print([search_desc(a, x) for x in a])15print(search_desc(a, 80), search_desc(a, 99), search_desc(a, 10))
Output
Press Run or Ctrl+Enter
Choose one

An unsorted list of 5000 user names; you check once whether one name is in it. What is simplest and fastest?

Summary

Take-away

Binary search: keep [lo, hi) true

  • Needs sorted data and indexing; at most n.bit_length() looks, linear search takes n
  • Half-open: hi = len(a), while lo < hi, lo = mid + 1, hi = mid
  • The range must shrink every round: lo = mid hangs, mixing the start and the loop misses numbers
  • Not found: lo stops where x would be inserted
  • Python ints don't overflow; C / Java write lo + (hi - lo) // 2
1lo, hi = 0, len(a)2while lo < hi:3    mid = (lo + hi) // 24    if a[mid] == x: return mid5    if a[mid] < x: lo = mid + 16    else: hi = mid