Mr. Sugeng halves the long floor to find one sack: lo, mid and hi at every step of code that really runs. What becomes of `lo = mid`, a fractional mid, an…
Why it matters
Binary search is everywhere: database indexes, git bisect, finding the version that broke things, guessing a limit. But it is fragile: one missing + 1 makes the while never stop, and an unsorted row makes its answer wrong without any error message.
The key idea
Every weighing throws away half, if the row is sorted
Common mistakes
The array is not sorted Binary search on unsorted data still runs, but its answer is nonsense: it throws away half on a weighing that means nothing. Sort first, or use a structure that is already sorted, like an index or a tree.
(lo + hi) / 2 not rounded In JavaScript the result can be a fraction, and a[3.5] is undefined. Use Math.floor. The lo + hi overflow is only a problem in languages with 32-bit integers (Java, C): write lo + (hi - lo) / 2 there; in JavaScript the numbers are doubles and safe.
The loop never stops If you write lo = mid (not mid + 1), the window can stick at two sacks. Always move past mid, and use the condition lo <= hi.
Thinking binary search finds the first one The plain search stops at whichever equal one it weighs first. For the first, use lower bound: hi = a.length, while (lo < hi), hi = mid.
Try it in this playground
One search until found A sorted row, the Math.floor code: watch the tarp cover half with each weighing.
An unsorted row fools it Search for a sack that is on an unsorted row, and see the answer come out wrong.
The code that sticks Use lo = mid and search for the heaviest sack.
A fractional index Drop Math.floor and see a[7.5] give undefined.