Sub topic 12
Using the Standard Library Instead of Writing Your Own
Earlier chapters showed that binary search is easy to get slightly wrong. A loop that is off by one, a midpoint that overflows, or a boundary convention applied inconsistently can each produce a bug that only appears on rare inputs. Most languages ship a tested binary search, and in production code you should usually call it instead of writing your own. This chapter covers two of them: Python's bisect module and Java's Arrays.binarySearch and Collections.binarySearch. You will learn what each one returns and which mistakes people commonly make with them.
This chapter assumes you have read the earlier chapters on lower-bound and upper-bound searches. You should know that a lower bound is the first index whose element is not less than the target, and an upper bound is the first index whose element is greater than the target. You should also know the half-open range convention [lo, hi).
Why Prefer the Library
Library implementations have three advantages over hand-written loops.
- Correctness. Many users have tested them on many inputs, including empty arrays, single elements, and duplicates.
- Speed. CPython's
bisectis written in C, so it runs faster than an equivalent Python loop. - Shared meaning. A reader who sees
bisect_leftknows exactly what it returns. A custom loop has to be read line by line.
Write your own only when the library cannot express what you need. Searching over a numeric answer range is one such case, and the next chapter covers it.
Python's `bisect` Module
The bisect module works on any sorted sequence that supports indexing. It never checks whether the sequence is actually sorted.
| Function | Returns or does | Equivalent concept |
|---|---|---|
| `bisect_left(a, x)` | First index `i` with `a[i] >= x` | Lower bound |
| `bisect_right(a, x)` | First index `i` with `a[i] > x` | Upper bound |
| `bisect(a, x)` | Same as `bisect_right` | Upper bound |
| `insort_left(a, x)` | Inserts `x` before any equal elements | Lower bound + insert |
| `insort_right(a, x)` / `insort(a, x)` | Inserts `x` after any equal elements | Upper bound + insert |
Every function also accepts optional lo and hi arguments, which limit the search to the half-open slice a[lo:hi]. The returned index is still an index into the whole list, not an offset into the slice.
Membership and Counting
bisect_left never returns -1. It returns an insertion point, so testing for membership takes one extra check:
import bisect
def index_of(a, x):
i = bisect.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
return -1
def count(a, x):
return bisect.bisect_right(a, x) - bisect.bisect_left(a, x)
a = [1, 3, 3, 3, 7]
print(index_of(a, 3)) # 1
print(index_of(a, 4)) # -1
print(index_of(a, 9)) # -1
print(count(a, 3)) # 3
print(count(a, 4)) # 0The i != len(a) check matters. If x is larger than every element, bisect_left returns len(a), and reading a[i] would raise IndexError.
Range Queries
The two bounds also count the elements inside a value range. The number of elements v with low <= v <= high is bisect_right(a, high) - bisect_left(a, low):
import bisect
temps = [12, 15, 15, 18, 21, 24, 24, 30]
low, high = 15, 24
n = bisect.bisect_right(temps, high) - bisect.bisect_left(temps, low)
print(n) # 6Mapping Values to Buckets
A common use of bisect_right is to look up which bucket a value falls into, given a sorted list of breakpoints:
import bisect
def grade(score, breakpoints=(60, 70, 80, 90), letters="FDCBA"):
return letters[bisect.bisect_right(breakpoints, score)]
print([grade(s) for s in (33, 60, 77, 89, 90, 100)])
# ['F', 'D', 'C', 'B', 'A', 'A']The choice of bisect_right puts a score of exactly 60 into the D bucket. With bisect_left, a score of 60 would get an F. When you pick between the two functions, you are deciding which side of each breakpoint the boundary value belongs to.
The `key` Parameter
Python 3.10 added a key argument. It lets you search a list of records sorted by one field:
import bisect
events = [(1, "boot"), (4, "login"), (9, "save"), (15, "logout")]
t = 9
i = bisect.bisect_left(events, t, key=lambda e: e[0])
print(i, events[i]) # 2 (9, 'save')
bisect.insort(events, (6, "edit"), key=lambda e: e[0])
print([e[0] for e in events]) # [1, 4, 6, 9, 15]The key argument behaves differently in the two kinds of function.
- In
bisect_leftandbisect_right,keyis applied to the list elements but not tox. You pass the key value (9), not a whole record. - In
insort,keyis applied toxas well, becausexis a whole record that is about to be inserted.
The list must be sorted by the same key you search with. If it is not, the results are meaningless.
Java's `Arrays.binarySearch`
Java takes a different approach. A single function reports two outcomes:
- If the key is found, it returns an index
i >= 0wherea[i]equals the key. - If the key is not found, it returns
-(insertionPoint) - 1. This value is always negative, even when the insertion point is 0.
The - 1 exists because -0 equals 0. Without it, "not found, insert at 0" would look the same as "found at index 0".
The following program covers the main overloads:
import java.util.ArrayList;
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};
System.out.println(Arrays.binarySearch(a, 7)); // 3
System.out.println(Arrays.binarySearch(a, 4)); // -3 (insert at 2)
System.out.println(Arrays.binarySearch(a, 0)); // -1 (insert at 0)
System.out.println(Arrays.binarySearch(a, 10)); // -6 (insert at 5)
// Range overload: searches a[1..4), result indexes the whole array
System.out.println(Arrays.binarySearch(a, 1, 4, 9)); // -5 (insert at 4)
// Keep a List sorted while inserting
List<Integer> list = new ArrayList<>(List.of(10, 20, 40));
int r = Collections.binarySearch(list, 30);
if (r < 0) {
list.add(-r - 1, 30);
}
System.out.println(list); // [10, 20, 30, 40]
// Search with a comparator; the list must be sorted by that comparator
List<String> names = List.of("Ana", "bob", "Cy");
System.out.println(
Collections.binarySearch(names, "BOB", String.CASE_INSENSITIVE_ORDER)); // 1
}
}The range overload binarySearch(a, fromIndex, toIndex, key) uses the half-open range [fromIndex, toIndex). Its encoded insertion point is an index into the whole array, the same convention Python uses for lo and hi.
Duplicates Are Not Handled for You
The Java documentation says that if the array contains several elements equal to the key, there is no guarantee which one is found. In practice you may get the middle copy. If you need the first or last occurrence, or a count, write a lower-bound or upper-bound loop like the one from the previous chapter. Java's TreeMap and TreeSet are another option. Their ceilingKey, floorKey, higher, and lower methods give bound-style queries on a sorted structure.
`Collections.binarySearch` on Linked Lists
Collections.binarySearch accepts any List. On a list that supports fast random access, such as ArrayList, it runs in O(log n). On a LinkedList it moves through the list with an iterator. It still makes only O(log n) comparisons, but reaching the middle element takes O(n) link traversals. Binary search on a linked list therefore takes linear time, which removes most of its advantage.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Searching an unsorted array | Wrong index or false "not found"; no error is raised | Sort first, or sort with the same comparator you search with |
| Treating `bisect_left`'s result as "found" | Wrong element returned for missing keys | Check `i < len(a) and a[i] == x` |
| Treating any negative Java result as -1 | Insertion point is lost | Compute `-r - 1` |
| Expecting the first duplicate from Java | Inconsistent index among equal keys | Write a lower-bound search |
| Sorting by one order, searching with another | Silent wrong answers | Use one comparator or key for both |
| Using `x in sorted_list` in Python | O(n) scan despite the sorted data | Use `bisect_left` plus an equality check |
Equivalents in Other Languages
| Language | Lower bound | Upper bound | Found-or-insertion |
|---|---|---|---|
| Python | `bisect.bisect_left` | `bisect.bisect_right` | Combine with equality check |
| Java | Hand-written or `TreeSet.ceiling` | Hand-written or `TreeSet.higher` | `Arrays.binarySearch` |
| C++ | `std::lower_bound` | `std::upper_bound` | `std::binary_search` (returns bool only) |
| Rust | `slice::partition_point` | `slice::partition_point` | `slice::binary_search` (returns `Result`) |
Learning the conventions of one library makes the others easier to pick up. Most of them return an insertion point in the half-open style, and most leave the sortedness check to you.
Exercise
In Java, Arrays.binarySearch(a, k) returns -1 for some sorted array a. What does this tell you about k and where it would be inserted?
Show answer
The key is not in the array. The insertion point is -(-1) - 1 = 0, so k is smaller than every element (or the array is empty) and belongs at index 0.
Exercise
Using only the bisect module, write an expression that counts how many elements of the sorted list a are strictly greater than 10 and strictly less than 20.
Show answer
bisect.bisect_left(a, 20) - bisect.bisect_right(a, 10). bisect_right(a, 10) skips past every element less than or equal to 10, and bisect_left(a, 20) stops before the first element greater than or equal to 20.
Exercise
A colleague keeps a Python list sorted by calling bisect.insort for each of 1,000,000 incoming values, then runs a few searches at the end. Why is this slow, and what should they do instead?
Show answer
Each insort shifts later elements, which takes O(n) time, so the whole process is O(n²). Since every insert happens before any search, they should append all values, call list.sort() once in O(n log n), and then use bisect for the searches.