Search in Python
Implement linear search and iterative binary search, then watch binary search fail on unsorted input to understand why sorted data is a hard requirement.
- Implement linear search in Python
- Implement binary search iteratively in Python
- Verify that binary search produces wrong answers on unsorted input
Two search algorithms, side by side. Read through both before running — focus on the loop structure and the invariant each one maintains.
Linear search and binary search
Reading the binary search loop
The loop maintains an invariant: if target is anywhere in the list, it
must be somewhere in lst[lo..hi]. Each iteration:
- Computes the midpoint —
(lo + hi) // 2avoids the integer overflow that(lo + hi) / 2can cause in languages with fixed-width integers. - Compares
lst[mid]totarget. - Narrows the range by moving
loup orhidown — always preserving the invariant.
When lo > hi, the range is empty: target is not in the list.
Why binary search fails on unsorted data
In the unsorted example above, binary_search compares the middle element and
then discards one half — but on unsorted data, the target might be in the
discarded half. The algorithm has no way to know. It gives a confident-looking
answer that is simply wrong.
This is not a bug to be fixed — it is a precondition violation. Always sort before calling binary search, or use linear search if you cannot guarantee order.
Python's standard library provides bisect.bisect_left(sorted_list, target)
for binary search. Use it in production code — it is correct and tested. The
hand-rolled version above is for learning the algorithm.
Where to go next
Next: Lab: search — time linear vs binary search on growing inputs, implement
a count-using-search function, and try a bonus recursive flatten.
Search concepts
Linear search scans every element — O(n). Binary search halves the search space each step — O(log n). The catch is that binary search only works on sorted data.
Lab: search
Time linear vs binary search on growing inputs, implement count_target with binary search, and flatten a nested list recursively as a bonus.