Binary search in practice
After this: Use bisect and Arrays.binarySearch, and read a negative return value.
On this page · 4 sections · 3 checks
So far you have written the loop yourself. At work you will rarely do that, because Python and Java already provide tested versions. You call them instead. The risk then changes: the common mistakes come from misreading what the library returns.
The library versions
Here are the library calls on the same ten-cell row.
from bisect import bisect_left, bisect_right, insort
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]i = bisect_left(nums, 23) # the first index whose value is >= 23print(i, nums[i] == 23) # 5 True: present, at index 5i = bisect_left(nums, 7)print(i, i < len(nums) and nums[i] == 7) # 2 False: missing, and 2 is where it would goinsort(nums, 7) # insert and keep the order (moving the cells costs O(n))print(nums[:4])
dupes = [1, 2, 2, 2, 3]print(bisect_left(dupes, 2), bisect_right(dupes, 2)) # the 2s occupy dupes[1:4]5 True 2 False [2, 5, 7, 8] 1 4
int[] nums = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};System.out.println(Arrays.binarySearch(nums, 23)); // 5: found at index 5int r = Arrays.binarySearch(nums, 7);System.out.println(r); // -3: negative means missingSystem.out.println(-r - 1); // 2: the insertion point, worked out from -(point) - 1
List<Integer> list = new ArrayList<>(List.of(2, 5, 8, 12));int at = -Collections.binarySearch(list, 7) - 1; // the same convention for a sorted Listlist.add(at, 7); // insert and keep the order (moving the cells costs O(n))System.out.println(list);5 -3 2 [2, 5, 7, 8, 12]
Python: bisect
Python's bisect_left(nums, x) is the one idea from the last lesson. It returns the first index whose value is at least x. If x is present, that is its first copy. If x is missing, that is its insertion point.
It never tells you which of the two happened, so you have to check. First check that i is inside the list, then check nums[i] == x.
bisect_rightreturns the index after the last copy, sobisect_right - bisect_leftcounts the copies. For[1, 2, 2, 2, 3]and 2, that is 4 − 1 = 3.insortinserts a value at its insertion point. Finding the place is fast, but moving the later cells along to make room is O(n), like any insert in the middle of an array.
Java: Arrays.binarySearch
Java's Arrays.binarySearch(nums, x) returns the index on a hit. On a miss it returns a negative number that also carries the insertion point: -(insertionPoint) - 1. Here is an example with 7 in the ten-cell row.
- 7 is missing, and its insertion point is 2.
- Java returns −(2) − 1, which is −3.
- You see a negative number, so you know that 7 is missing.
- You get the insertion point back with
-result - 1, which is −(−3) − 1 = 2.
Why is there an extra −1? Without it, an insertion point of 0 would come back as 0, which looks like a hit at index 0. With it, that case comes back as −1. Collections.binarySearch works the same way for a sorted List.
The calls side by side
| Question | Python | Java | Cost |
|---|---|---|---|
| Is x here, and where? | i = bisect_left(nums, x), then i < len(nums) and nums[i] == x | Arrays.binarySearch(nums, x) >= 0 | O(log n) |
| Where would x go? | bisect_left(nums, x) | -Arrays.binarySearch(nums, x) - 1 (when negative) | O(log n) |
| How many copies of x? | bisect_right(nums, x) - bisect_left(nums, x) | two hand-written searches | O(log n) |
| Insert x, keeping the order | insort(nums, x) | list.add(point, x) | O(log n) to find, O(n) to move the cells |
x in nums / list.contains(x) | a linear scan, even when sorted | a linear scan, even when sorted | O(n) |
When binary search applies
Binary search needs two things: the data is sorted, and any index can be read in O(1), which means in the same small number of steps however big the data is. A sorted array has both.
A sorted linked list has only the first. In a linked list, each item knows only where the next item is, so finding the middle means walking through half of the list. A "binary search" over a linked list therefore costs O(n) anyway.
What about data that is not sorted yet? Sorting n values takes about n × log₂ n steps, which is written O(n log n). So it depends on how many searches you need. Here is an example with a million values, where log₂ n is about 20.
- One search. A scan takes up to a million steps. Sorting first takes about 20 million steps. The scan wins.
- A hundred searches. Scanning each time takes up to 100 million steps. Sorting once takes about 20 million steps, and then each search takes about 20. Sorting wins.
Binary search also answers questions about order: the nearest value, the next larger value, how many values are below this one, where a value would go. A hash map is a structure that answers "is this key here?" in O(1) on average, but it keeps its keys in no useful order, so it cannot answer any of those questions.
Check yourself
Java's Arrays.binarySearch(nums, 7) on [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] returns −3. What does that tell you?
dupes = [1, 2, 2, 2, 3]. What do bisect_left(dupes, 2) and bisect_right(dupes, 2) return, and how many 2s are there?dupes = [1, 2, 2, 2, 3]. Arrays.binarySearch(dupes, 2) may land on any of the 2s, so you write two searches. One is firstOccurrence(dupes, 2) from the lesson on the first copy. The other is its mirror image, which sets lo = mid + 1 after a hit and returns lo, the first index whose value is greater than 2. What do the two return, and how many 2s are there?
You have a sorted array of a million timestamps. You must answer “how many are before t?” for many different values of t, and most of those values are not in the array. What is the right tool?
Connect
- Use bisect_left and bisect_right in Python, and Arrays.binarySearch in Java.
- Read a negative Java result: it is −(insertion point) − 1.
- Ask “is it sorted?” first, and say why a linked list or a single search is not a job for binary search.