Sub topic 5
Why Binary Search Needs Sorted Data
This chapter assumes you can read short Python functions, know zero-based indexing, and have seen linear search and its O(n) cost in earlier chapters. You do not need to know how binary search works line by line yet. The next chapter builds it step by step. This chapter covers the condition binary search depends on, and what goes wrong when that condition does not hold.
The Promise That Makes Halving Possible
Linear search learns one fact per comparison: whether that one element matches. Binary search learns much more from each comparison. When it looks at the middle element and sees that it is smaller than the target, it rules out the middle element and every element to its left.
That conclusion is only valid because of a promise about the data. If the list is sorted in non-decreasing order, then for any indices i < j we have a[i] <= a[j]. So when a[mid] < target, every a[i] with i <= mid satisfies a[i] <= a[mid] < target. None of those elements can equal the target. One comparison discards half the range without anyone looking at those elements.
Take the promise away and the conclusion has nothing to rest on. An element to the left of mid could be anything, including the target.
Watching It Break on Unsorted Input
The function below is a standard binary search. Its details are the subject of the next chapter. Here it is only a test subject.
def binary_search(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
elif a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
data = [4, 2, 7, 1, 9]
print(binary_search(data, 1)) # -1, but 1 is at index 3
print(binary_search(data, 7)) # 2, found by luck
print(binary_search(sorted(data), 1)) # 0, correct on sorted inputHere is the trace for target 1 on [4, 2, 7, 1, 9]:
| Step | lo | hi | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 4 | 2 | 7 | 7 > 1, so hi = 1 (indices 2 to 4 discarded, including index 3) |
| 2 | 0 | 1 | 0 | 4 | 4 > 1, so hi = -1 |
| 3 | 0 | -1 | lo > hi, return -1 |
The search threw away index 3 in its first step. It reasoned that everything right of a 7 must be at least 7. In an unsorted list that reasoning is false.
The failure is silent and intermittent
Look at the second call. Searching for 7 succeeds because 7 happens to sit at the first midpoint. This is why the bug is dangerous. Some lookups work, so a quick test can pass. Nothing raises an exception. The function simply returns "not found" for a value that is present.
Which errors can and cannot happen
The plain equality version above has an asymmetry worth knowing:
- False negatives are possible. The target is present, and the search reports -1.
- False positives are not. The function returns
midonly after checkinga[mid] == target, so any index it returns really holds the target.
Variants that return a position without an equality check, such as the lower-bound search covered later, lose that guarantee. On unsorted input they return a plausible-looking insertion index that is simply wrong. Code that uses that index to insert data then corrupts the order even further.
"Sorted" Means Sorted by the Same Rule You Search With
A list is not sorted in general. It is sorted with respect to an ordering. Binary search compares with some ordering too, usually the language's default <. The two orderings must be the same. Mismatches are the most common real-world cause of this bug, because the list looks sorted to a human.
Descending order
desc = [9, 7, 5, 3, 1]
print(binary_search(desc, 3)) # -1, but 3 is at index 3The list is perfectly ordered, just in the opposite direction from what the search assumes. At mid = 2, it sees 5 > 3 and discards the right half, which is exactly where 3 lives. To search descending data, either reverse the comparisons or search a reversed copy.
A custom sort key
names = sorted(["carol", "Bob", "alice"], key=str.lower)
print(names) # ['alice', 'Bob', 'carol']
print(binary_search(names, "alice")) # -1, but "alice" is at index 0The list is sorted case-insensitively. The search uses Python's default string comparison, where every uppercase letter sorts before every lowercase letter ("B" < "a"). Under that ordering, ['alice', 'Bob', 'carol'] is not sorted. At mid = 1 the search sees "Bob" < "alice" and moves right, skipping index 0.
The fix is to search with the same key. Lowercase the target and compare it against lowercased elements, or keep a parallel list of keys built with the same key function.
Other ways the ordering can drift
| Situation | Why the order no longer matches |
|---|---|
| Sorted by one field, searched by another | Records sorted by `last_name` are in arbitrary order by `id` |
| Locale-aware sort, byte-wise search | Accented characters and case order differently |
| Numbers stored as strings | `"10" < "9"` as strings, but 10 > 9 as numbers |
| Floating-point `NaN` in the data | `NaN` compares false with everything, so there is no consistent order |
| Data changed after sorting | An append or in-place edit breaks the order at one spot |
The Weaker Condition Binary Search Actually Uses
For a single search for a specific target, binary search does not strictly need the whole list sorted. It needs the list to be partitioned around that target. That means all elements less than the target come first, then all elements equal to it, then all elements greater.
partitioned = [2, 1, 3, 5, 5, 9, 7] # not sorted, but split cleanly around 5
print(binary_search(partitioned, 5)) # 3Every element left of the 5s is smaller, and every element right of them is larger, so each discard decision is still correct for target 5. The same list is not partitioned around 1 or 9, and searching for those can fail.
A sorted list is partitioned around every possible target at once, which is why sorting is the practical requirement. The weaker view matters later. Binary search on a monotonic predicate depends on exactly this idea: a condition that is false for a prefix of the range and true for the rest.
Can You Just Check First?
A natural defensive move is to verify sortedness before searching:
def is_sorted(a):
return all(a[i] <= a[i + 1] for i in range(len(a) - 1))
print(is_sorted([1, 3, 3, 7])) # True
print(is_sorted([4, 2, 7, 1])) # FalseThis check costs O(n), because it has to look at every adjacent pair. If you run it before every search, you have paid for a linear scan, and a linear search would have found the answer in the same time. The check wipes out the reason for using binary search.
Better places to enforce the precondition:
- At construction. Sort once when the collection is built, or check once when it arrives from outside.
- At mutation. Insert new elements at their sorted position instead of appending. A later chapter shows
bisect.insortfor this. - In debug builds or tests. An
assert is_sorted(a)that runs during testing catches ordering bugs without slowing production. - By type. Wrap the data in a class whose only insert method keeps it sorted, so unsorted states cannot exist.
What Sorting Costs
If your data does not arrive sorted, you have to pay for sorting. A comparison sort takes O(n log n) time, which is more than a single linear search's O(n). Sorting just to run one search is a loss.
The trade only pays off when you search the same data many times. Sorting once and then running k binary searches costs about n log n + k log n comparisons. Running k linear searches costs about k·n. For large n, sorting wins once k grows past roughly log n searches. A later chapter turns this into a full decision guide. The point for now is that the precondition has a price, and that price is paid once per batch of changes, not once per search.
Summary of Failure Modes
| Cause | Symptom | Fix |
|---|---|---|
| Data never sorted | Present values reported missing, intermittently | Sort once before searching |
| Sorted descending | Most lookups miss | Reverse comparisons or the data |
| Different key or comparator | Lookups miss on mixed case, strings vs numbers | Search with the same key used to sort |
| Mutated after sorting | Failures near the modified spot | Insert in sorted position |
| `NaN` or inconsistent comparisons | Unpredictable results | Remove or handle such values before sorting |
Exercise
Trace binary_search([3, 8, 1, 6, 2], 2) using the function from this chapter. What does it return, and at which step does it discard the target?
Show answer
It returns -1. Step 1: lo=0, hi=4, mid=2, a[2]=1 < 2, so lo=3. Step 2: lo=3, hi=4, mid=3, a[3]=6 > 2, so hi=2. Now lo > hi and it returns -1. The target at index 4 was discarded in step 2, because the search assumed every element right of the 6 was at least 6.
Exercise
A list of product codes was sorted with sorted(codes, key=int), where each code is a digit string such as "9" or "10". A binary search then compares the string target directly with the string elements. Give a concrete list where this fails, and explain why.
Show answer
Take ["9", "10", "11"]. It is sorted numerically, but as strings "10" < "11" < "9". Searching for "9": lo=0, hi=2, mid=1, "10" < "9" as strings is True, so lo=2. mid=2, "11" < "9" is True, so lo=3. Now lo > hi and the search returns -1, even though "9" is at index 0. The data was sorted by one ordering (int) and searched with another (string). The fix is to compare int(target) against int(element).
Exercise
Your service receives a fresh unsorted list of 1,000,000 IDs and must answer exactly one membership query against it before discarding the list. Should you sort and binary search, or linear search? Justify with approximate operation counts.
Show answer
Use linear search. It costs at most about 1,000,000 comparisons. Sorting costs roughly n log2 n, which is about 1,000,000 × 20 = 20,000,000 comparisons, before the roughly 20-step binary search even starts. Sorting only pays off when the same list answers many queries.