Find the bug · #58 · Sort and search Medium C++
Some orders can’t be found
A binary search over order ids finds some orders and misses others that are definitely there.
On this page
The report
Order ids are kept sorted, and lookups use a binary search. Some orders that definitely exist come back “not found”, including the newest one and any order in a list of one.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Index of target in a sorted list of order ids, or -1.
int findOrder(const vector<int>& ids, int target) {
int lo = 0, hi = (int)ids.size() - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (ids[mid] == target) return mid;
if (ids[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}Read it, then pick a line.
When lo and hi are equal, there’s one candidate left. Does the loop check it?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
vector<int> ids = {10, 20, 30, 40, 50};
cout << findOrder(ids, 30) << " " << findOrder(ids, 20) << " " << findOrder(ids, 50) << endl;It prints
2 -1 -1
It should print
2 1 4
Show the answer: the bug, the fix, and how you’d find it
The bug (line 4)
Line 4 loops while lo < hi, but hi here is the last index that could still hold the target (it’s inclusive). When the search narrows down to a single candidate, lo == hi, the loop stops without checking it. With an inclusive hi, the loop must run while lo <= hi.
The fix
1// Index of target in a sorted list of order ids, or -1.2int findOrder(const vector<int>& ids, int target) {3 int lo = 0, hi = (int)ids.size() - 1;4 while (lo < hi) {4 while (lo <= hi) {5 int mid = lo + (hi - lo) / 2;6 if (ids[mid] == target) return mid;7 if (ids[mid] < target) lo = mid + 1;How you’d find it
- Reproduce with a few targets: the middle one is found, 20 and 50 aren’t. A list with one id never finds it.
- Trace 50: lo and hi close in until both are 4, then the loop ends without looking at index 4.
- Decide what
himeans: it starts atsize - 1, so it’s inclusive, and the loop condition has to match.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
CHECK(findOrder({7}, 7) == 0);
CHECK(findOrder({10, 20, 30, 40, 50}, 50) == 4);
CHECK(findOrder({10, 20, 30, 40, 50}, 20) == 1);
CHECK(findOrder({10, 20}, 15) == -1);
CHECK(findOrder({}, 3) == -1);Where else this bites
- The opposite mistake,
hi = midwithlo <= hi, loops forever. - Compare “A new high score never goes last”, which uses exclusive bounds correctly.