Sub topic 7
The simplest implementation: a sorted array with binary search
This chapter assumes you know Big-O notation, how binary search works, and how arrays differ from linked structures. You have already seen the ordered map operations (floor, ceiling, range views). Here you build them on the simplest possible storage: one array kept in sorted order.
The idea
Keep keys in a contiguous array, sorted by the key order. Binary search finds any key, or the place where it would go, in O(log n) comparisons. Every navigation operation then becomes "find a position, then look at a neighbor."
Python's bisect module provides the two boundary searches you need:
bisect_left(a, x)returns the first index wherexcould be inserted while keeping order. It lands before any equal elements.bisect_right(a, x)returns the index after the last element equal tox.
Insert and range query
insort finds the position with binary search and then inserts there. The search is cheap, but the insert shifts every later element one slot to the right.
from bisect import bisect_left, bisect_right, insort
scores = []
for s in [50, 20, 40, 20, 30]:
insort(scores, s)
print(scores) # [20, 20, 30, 40, 50]
lo = bisect_left(scores, 20) # 0
hi = bisect_right(scores, 40) # 4
print(scores[lo:hi]) # [20, 20, 30, 40]A range query is two binary searches and one slice. The slice copies only the matching elements, so the cost is O(log n + k) for k results. Use bisect_left for an inclusive lower bound and bisect_right for an inclusive upper bound. Swap them to get exclusive bounds.
Navigation operations
Each operation maps to one search:
| Operation | How to compute it |
|---|---|
| first, last | `a[0]`, `a[-1]` |
| ceiling(x), smallest key >= x | `a[bisect_left(a, x)]` |
| higher(x), smallest key > x | `a[bisect_right(a, x)]` |
| floor(x), largest key <= x | `a[bisect_right(a, x) - 1]` |
| lower(x), largest key < x | `a[bisect_left(a, x) - 1]` |
Check the index before you use it. A ceiling search can return len(a), and a floor search can return -1, which Python would silently read as the last element.
from bisect import bisect_right
def floor(a, x):
i = bisect_right(a, x)
return a[i - 1] if i > 0 else None
print(floor([60, 70, 80, 90], 85)) # 80
print(floor([60, 70, 80, 90], 10)) # NoneStoring a map
For a map, keep two parallel arrays: sorted keys and their values at the same indexes. Search the key array, then insert into both at the same position. Another option is one array of key-value pairs, but then bisect needs a key function (the key= argument, available since Python 3.10).
Cost
| Operation | Cost |
|---|---|
| Lookup, floor, ceiling | O(log n) |
| Range query | O(log n + k) |
| Insert, delete | O(n), because of shifting |
| Memory | Compact, with no per-node pointers |
The shifting is a fast memory move, so it is cheap for thousands of keys and painful for millions with frequent writes.
The next chapters cover trees and other structures that keep O(log n) searches while avoiding the O(n) insert.
Exercise
A sorted list is [10, 20, 20, 30]. What do bisectleft(a, 20) and bisectright(a, 20) return, and how do you use them to count the 20s?
Show answer
bisectleft returns 1 and bisectright returns 3. The count of 20s is bisectright - bisectleft = 2.
Exercise
Why is a sorted array a poor choice for a map that receives millions of inserts at random positions?
Show answer
Each insert shifts, on average, half of the elements, so it costs O(n). Millions of inserts then cost far more than the O(log n) per insert of a balanced tree.