Sub topic 12
Using the Standard Library Instead of Writing Your Own
This chapter assumes you know how binary search works, including the lower-bound and upper-bound variants from the previous chapter. It also assumes you can read basic Python and Java. Most languages ship tested binary search functions. Use them unless you have a specific reason not to. Your own version can have an off-by-one bug, while the library version has been tested by a very large number of users.
Python: the `bisect` module
The bisect module works on any sorted list. It never checks whether the list is sorted. If the list is out of order, it still returns an index, but that index has no meaning.
| Function | Returns |
|---|---|
| `bisect_left(a, x)` | First index `i` where `a[i] >= x` (lower bound) |
| `bisect_right(a, x)` | First index `i` where `a[i] > x` (upper bound) |
| `insort_left(a, x)` / `insort(a, x)` | Inserts `x` and keeps `a` sorted |
bisect and insort are aliases for bisect_right and insort_right.
import bisect
a = [1, 3, 3, 3, 7]
def contains(a, x):
i = bisect.bisect_left(a, x)
return i < len(a) and a[i] == x
print(contains(a, 3)) # True
print(contains(a, 4)) # False
# Count values in the range [2, 6]
print(bisect.bisect_right(a, 6) - bisect.bisect_left(a, 2)) # 3
# Search records by a field (Python 3.10+)
people = [("Ana", 25), ("Bo", 30), ("Cy", 41)]
i = bisect.bisect_left(people, 30, key=lambda p: p[1])
print(people[i]) # ('Bo', 30)bisect_left does not tell you whether the value is present. You have to do the contains check yourself.
insort finds the position in O(log n) time, but inserting into a list shifts the elements after it, which takes O(n). If you insert many times into a large list, consider a sorted container or a heap.
Java: `Arrays.binarySearch` and `Collections.binarySearch`
Java packs two answers into one int. A result of zero or more is the index of a match. A negative result encodes the insertion point as -(insertionPoint) - 1. The extra -1 exists so that insertion point 0 still gives a negative number.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SearchDemo {
public static void main(String[] args) {
int[] a = {1, 3, 5, 7, 9};
int found = Arrays.binarySearch(a, 7); // 3
int missing = Arrays.binarySearch(a, 4); // -3
int insertionPoint = -missing - 1; // 2
System.out.println(found + " " + missing + " " + insertionPoint);
List<String> names = List.of("ana", "bo", "cy");
System.out.println(Collections.binarySearch(names, "bo")); // 1
// Search a subrange [fromIndex, toIndex)
System.out.println(Arrays.binarySearch(a, 1, 4, 5)); // 2
}
}Common mistakes
- Testing
result != -1in Java. A missing key can return any negative number, such as-3. Testresult >= 0instead. - Expecting the first duplicate. Java makes no guarantee about which of several equal elements it returns. If you need the first one, use your own lower bound. In Python, use
bisect_left. - Searching unsorted data. Neither library checks the order of the data. Sort it first, with the same ordering (comparator or key) that you use for the search.
- Mismatched comparators.
Collections.binarySearch(list, key, cmp)requires that the list was sorted by the samecmp.
Exercise
In Java, Arrays.binarySearch(a, 10) on int[] a = {2, 4, 6, 8} returns what, and what insertion point does it encode?
Show answer
10 is larger than every element, so the insertion point is 4. The method returns -(4) - 1 = -5.
Exercise
Using only bisect, write an expression that counts how many elements of a sorted list a are strictly less than x.
Show answer
bisect.bisect_left(a, x). The lower-bound index equals the number of elements less than x.