searching
Sequential search is reviewed in the performance chapter and binary search gets its own chapter That tells you something about how easily binary search goes wrong
Linear search
#include <vector>
long linear(const std::vector<int> &items, int target) {
for (std::size_t i = 0; i < items.size(); ++i)
if (items[i] == target) return static_cast<long>(i);
return -1;
}
It works on anything It makes no demands It is the right answer for small lists and one off checks
Binary search
long binary(const std::vector<int> &items, int target) {
long lo = 0, hi = static_cast<long>(items.size()) - 1;
while (lo <= hi) {
long mid = lo + (hi - lo) / 2;
if (items[mid] == target) return mid;
if (items[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
On [22, 80, 443], searching for 443 returns index two
Searching for 999 returns minus one
Why lo + (hi - lo) / 2
(lo + hi) / 2 can overflow when both indices are large
The alternative cannot
That is one character of difference between correct and undefined behaviour
C++ does not catch it for you
The precondition
The data must be sorted according to the same comparison the search uses If it is not, the algorithm does not crash It returns a wrong answer with complete confidence
That is the dangerous kind of bug A crash stops you A plausible wrong answer keeps going and writes a report
The mental model
Think of a dictionary with every page marked Open in the middle The word you want is before or after Throw away half the work Repeat
Fourteen steps cover about ten thousand entries That is the power of halving
Off by one
lo <= hi versus lo < hi
mid + 1 versus mid
hi = mid versus hi = mid - 1
Those three choices are where binary search implementations die
Write the invariant down: the answer, if it exists, is always inside [lo, hi]
Every update must preserve that statement
When not to use it
- unsorted data
- data that changes between comparisons
- very small lists, where linear is simpler
- repeated membership, where an unordered_set is better
Real use
A sorted vector of port numbers from a scan A version timeline A ranges table in a firewall rule set All are binary search shapes
Exercises
- Implement binary search from memory and test an empty vector
- Run it on unsorted data and watch it return a wrong answer
- Change the comparison to descending order and fix the branches
- Explain the invariant in one sentence
What to remember
Binary search trades a precondition for speed If you cannot guarantee the precondition, you cannot trust the answer
Posted