Halve the Search Space

If someone asks you to find a name in a printed phone book, you don’t read it from the first page. You open it near the middle, see whether the name comes before or after that page, and throw away the half that can’t hold it. After about twenty of those steps, a million entries are down to one.

Binary search is that habit written as a loop. Like the two pointers you practiced earlier, it relies on order. It needs one thing from the data: an order that tells you, from a single comparison, which half to keep.

Keep the Half That Can Still Hold the Answer

Track the part of the array that’s still in play with two indexes, low and high. Look at the middle item, compare, and move one of the bounds past it:

Language: JavaScript
const releases = [3, 8, 15, 21, 34, 40, 52];

function findRelease(builds, target) {
  let low = 0;
  let high = builds.length - 1;
  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    if (builds[mid] === target) return mid;
    if (builds[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return -1;
}

console.log(findRelease(releases, 34), findRelease(releases, 9));

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.