Sub topic 5
Why Binary Search Needs Sorted Data
This chapter assumes you can read Python, know zero-based indexing, and have met linear search and Big-O notation in earlier chapters. You do not need to know how binary search is coded yet. The next chapter covers that. This chapter explains the one condition binary search depends on and what goes wrong when that condition does not hold.
The idea behind halving
Linear search learns very little from each comparison. If a[i] is not the target, the only thing it rules out is position i. Binary search learns much more. It looks at the middle element and compares it to the target. If the target is smaller, it throws away the middle element and everything to its right.
That step is only safe if every element to the right of the middle is at least as large as the middle element. This is what "sorted" means here: for every pair of neighbours, a[i] <= a[i + 1]. This condition is a precondition. A precondition is something the caller must guarantee before calling the function. The function does not check it.
What breaks without it
Binary search on unsorted data does not crash or raise an error. It returns -1 for a value that is in the list, or it returns an index by luck. Because the failure is silent, it is easy to miss.
Here is a trace that searches for 2 in the unsorted list [4, 9, 1, 7, 3, 8, 2]. The 2 is at index 6.
| Step | lo | hi | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 7 | 2 < 7, discard indices 3–6 |
| 2 | 0 | 2 | 1 | 9 | 2 < 9, discard indices 1–2 |
| 3 | 0 | 0 | 0 | 4 | 2 < 4, discard index 0 |
| 4 | 0 | -1 | — | — | range empty, return -1 |
The first step threw away index 6, which held the answer. Every comparison after that searched the wrong part of the list.
Sorted by which ordering?
"Sorted" always means sorted by the same comparison the search uses. A list sorted case-insensitively is not sorted under Python's default string comparison. Python compares strings by character code, so every uppercase letter comes before every lowercase letter.
def is_sorted(a, key=lambda x: x):
return all(key(a[i]) <= key(a[i + 1]) for i in range(len(a) - 1))
words = sorted(["banana", "apple", "Cherry"], key=str.lower)
print(words) # ['apple', 'banana', 'Cherry']
print(is_sorted(words, key=str.lower)) # True
print(is_sorted(words)) # FalseIf you sort with key=str.lower and then search with plain <, the search can discard the half that holds the target. Descending order causes the same mismatch: a search written for ascending order will move in the wrong direction on every step.
The cost of the precondition
The precondition has a cost. Sorting takes O(n log n) time. If you search once, a linear search at O(n) is cheaper than sorting first. Sorting pays off when you search the same data many times. Inserting into a sorted list also costs O(n), because the later elements have to shift over by one. The final chapter weighs these trade-offs in detail.
Exercise
A list holds [10, 20, 30, 25, 40, 50]. One element is out of place. Using lo = 0, hi = 5, and mid = (lo + hi) // 2, does a binary search for 25 find it? Which target values in this list would it fail to find?
Show answer
No. The first mid is 2, and 25 < 30, so hi becomes 1. The value 25 is at index 3, which has now been discarded, so the search returns -1. Tracing each target shows that only 25 fails. The searches for 10 and 20 stay in indices 0–1, which are in order. The searches for 30, 40, and 50 go right from index 2 and never compare against 25 in a way that misleads them. A single misplaced element can hide itself and leave every other search working, which makes this kind of bug hard to spot.