Linear and Binary Search
Searching is everywhere - finding a product, a word, a user. Checking items one by one is O(n); if the data is sorted, binary search cuts the remaining range in half each step, finding anything among a million items in about 20 checks.
Linear search - O(n)
Check items one by one. Works on any list, sorted or not.
Example
Binary search - O(log n)
On a sorted list, look at the middle. If the target is bigger, throw away the left half; if smaller, the right half. A million items need only about 20 steps.
Example
Binary search on the answer
The same idea finds the smallest value that works. Example: the smallest daily capacity to ship all parcels within D days.
Example
Python's
bisect module does binary search for you: bisect.bisect_left(prices, 499) gives 4.Key points
- Linear search is O(n) and works on any data.
- Binary search is O(log n) but needs sorted data.
- Binary search also works on answers (search the answer space).
📝 Test yourself
1. What must be true before binary search works?
2. About how many steps does binary search need for 1,000,000 items?
3. Fill in the middle index calculation:
mid = (lo + hi) 2
