Data Structures & Algorithms / Module 4: Searching and sorting
Topic 4.1
Linear search vs binary search
On sorted data, every guess throws away half the possibilities: a million items take about 20 steps.
Watch: every step throws away half the remaining blocks. Compare binary search's step count with searching one by one.
Like a number-guessing game
A friend thinks of a number from 1 to 100 and will only answer "higher" or "lower". Guessing 1, 2, 3 and so on can take 100 guesses. A smart player guesses 50 first. If the answer is "higher", 1 to 50 are gone in one go. The next guess is 75, then 63, and so on. Seven guesses at most.
That is binary search. In the figure the blocks are sorted from small to large. Press Step and watch: the middle block is compared with the target, then the half that can't contain it dims.
How fast is it?
Every step throws away half. So twice as much data needs just one more step:
| Items | One by one (worst case) | Binary search (worst case) |
|---|---|---|
| 16 | 16 | 5 |
| 1,000 | 1,000 | 10 |
| 1,000,000 | 1,000,000 | 20 |
| 1,000,000,000 | 1,000,000,000 | 30 |
In Big-O terms, checking one by one is O(n) and binary search is O(log n).
The catch: the data must be sorted
Throwing half away is only allowed if we are sure everything on the left is smaller and everything on the right is larger. On shuffled data, binary search still gives an answer, but it can be wrong, and no error warns you. Sorting first takes time too, so it only pays off when you will search many times.
Code, for programmersBinary search, explained line by line
function binarySearch(list, target) {
let lo = 0; // left edge of what is still possible
let hi = list.length - 1; // right edge
while (lo <= hi) { // stop when nothing is left
const mid = lo + ((hi - lo) >> 1); // the middle
if (list[mid] === target) return mid;
if (list[mid] < target) lo = mid + 1; // too small: drop the left half
else hi = mid - 1; // too big: drop the right half
}
return -1; // nothing left: it isn't there
}Where the idea is used
- Databases find one row among millions in a few steps, using a search much like this one (an index).
- Finding when a bug appeared: git bisect tests the version in the middle of the history, then throws half away.
- Finding a limit, such as the largest image size that still fits, by guessing in the middle and narrowing down.
Quiz
What must be true for binary search to give the right answer?
At most how many steps to search 1,000 sorted items?
The middle value is smaller than what you are looking for. What next?
You have 1 million shuffled items and will search them only once. Best choice?
0 of 4 answered.