Grade 12 Computer Science · Searching and sorting
Two searches and one condition
Why the faster one is not always possible.
Not found — and the item was there all along
The fast search runs on an array, gives no error, does not hang, and returns -1: the item was not found. But the item is in the array. And in the same code, the middle is computed in a clumsy way when a plain add-and-divide seems to give the same number. What does the code know that we forget?
In grade eight you met the two searches, and in grade nine you saw why the halving works. Now we shall write them exactly and notice one detail people tend to skip: the condition without which the fast one simply returns a wrong answer.
static int binary(int[] a, int wanted) {
int lo = 0, hi = a.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2; // safe against overflow
if (a[mid] == wanted) return mid;
if (a[mid] < wanted) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}Two details in the middle line
The form of computing the middle looks needlessly clumsy, and it has two good reasons. The first: adding two large bounds can overflow past the type’s upper limit, and the written form prevents that. The second: this computation is whole-number division, so the middle leans slightly leftward — and that is why the loop’s condition uses “at most” and not “less than”. Both those details look technical and both are known sources of bugs.
| The search | Condition | Cost |
|---|---|---|
| Item by item | None | Linear |
| By halving | The data is sorted | Logarithmic |
Example 1 — why halving on unsorted data is silent
- It checks the middle and decides a side.
- The decision assumes sorting.
- And without it it turns to the wrong side.
Example 2 — why the middle leans leftward
- The division is whole-number division.
- And the fraction is erased downward.
- So the condition is “at most”.