Video in progress

Write binary search iteratively and explain the trap in computing the midpoint.

I keep the lo and hi bounds, compare the middle element with the target and discard the half I don't need. I compute the midpoint as lo + (hi - lo) / 2, because (lo + hi) / 2 causes an int overflow on large indexes.

📖 Answer

static int search(int[] a, int target) {
    int lo = 0, hi = a.length - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;   // not (lo + hi) / 2
        if (a[mid] == target) return mid;
        if (a[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return -1;
}

The history of the overflow is interesting: this very bug lived in the JDK itself for years. If lo + hi exceeds 2³¹, the result goes negative and you get an ArrayIndexOutOfBoundsException. It takes an array with billions of elements, but interviewers expect you to know about it. (lo + hi) >>> 1 is also a correct variant.

Two more common mistakes:

  • writing while (lo < hi) and skipping the check of a one-element range;
  • writing lo = mid or hi = mid and ending up in an infinite loop.

To verify, walk through by hand with arrays of 0, 1 and 2 elements, and with the target at either edge.