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.

A moving boundary is the idea shared by nearly every algorithm in the unit.
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 searchConditionCost
Item by itemNoneLinear
By halvingThe data is sortedLogarithmic

Example 1 — why halving on unsorted data is silent

  1. It checks the middle and decides a side.
  2. The decision assumes sorting.
  3. And without it it turns to the wrong side.

Example 2 — why the middle leans leftward

  1. The division is whole-number division.
  2. And the fraction is erased downward.
  3. So the condition is “at most”.
Every decision on lines 6 and 7 assumes the array is sorted — and the code does not check that.