Binary search
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:
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")
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.
9 elements, each as likely to be looked for as any other. On average, how many comparisons does a successful sequential search take (ASL)?
The data is in a sorted singly linked list. Why not use binary search?
a[mid] is one step away. In a list, getting to element mid means walking from the head, O(n) just to get there, slower than sequential search. Either use an array, or use a binary search tree.1,000,000 sorted numbers. How many looks does binary search need at most?
(10**6).bit_length(). 1000 is √n and 500000 is n / 2; neither is binary search.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, likea[0:len(a)]. - Go on while the range holds something:
while lo < hi. Whenlo == hithe 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 writingmidleaves exactly mid out.
lo↑hi↑mid1lo, 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
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.
lo↑hi↑mid1lo, 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
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))
[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".
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?
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))
hi = mid drops exactly the mid you just checked. mid - 1 throws away the one to its left as well, which is how 3 gets lost. lo is worse: it empties the whole range at once.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).
[0, 1, 2, 3, 4, 5] -1 -1 -1 -1
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))
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):
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])
lo < hi treats hi as "not included": index 3 is outside the range from the very start. Looking for 7, lo moves right until it reaches 3, lo == hi, and the loop stops: the last element can never be found. The one-element [7] fails the same way: hi = 0, the loop never even starts.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:
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)
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 - 1in 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.
lo↑hi↑mid1lo, 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
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.
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))
[0, 1, 2, 3] -1
lo < hi, hi = mid), so the start has to keep the same promise: the answer is in a[lo:hi], and hi points just past the last one, hi = len(a). The other fix is to make the whole thing closed, which means changing three places.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:
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)
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) | |
|---|---|---|
| Start | hi = len(a) - 1 | hi = len(a) |
| Loop condition | lo <= hi | lo < hi |
a[mid] < x | lo = mid + 1 | lo = mid + 1 |
a[mid] > x | hi = mid - 1 | hi = mid |
| Stops (not found) at | lo == hi + 1 | lo == 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.
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?
hi - lo is only 0.5 billion; added to lo it makes 1.75 billion, never past hi, so nothing overflows. 1.5 and 2 billion themselves still fit in an int.You switch to a closed range [lo, hi]. Which set of lines is right?
lo == hi there's still one left to look at, hence <=; mid has been checked and must go, hi = mid - 1. The second set is mixed from this lesson's three bugs; the third reads a[len(a)], out of range; the fourth gets stuck when x isn't there.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:
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
5 -1 -1 5 True True
| Code | Needs | Time |
|---|---|---|
x in a, a.index(x) | nothing | O(n): it doesn't know a is sorted |
bisect_left(a, x) + one look | a already sorted | O(log n) |
x in s (s a set) | hashable elements | O(1) on average, but no order |
sorted(a) first, then binary search | nothing | sorting 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).
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.
[0, 1, 2, 3, 4, 5] -1 -1 -1
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))
An unsorted list of 5000 user names; you check once whether one name is in it. What is simplest and fastest?
in walks the list once, O(n), and that's enough. Sorting first costs O(n log n), and building a set also has to put all n in: both are slower than one walk. Building a set or sorting pays off only when you look up many times. Binary search on unsorted data simply gives wrong answers.Summary
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