Find a course

Module 3: Searching and SortingLesson 7 of 1312 min

Binary Search

Implement binary search without off-by-one bugs, see why it needs sorted data with random access, and apply the halving idea to search for answers.

Step 1 of 10Learn

Halving the problem

You met the idea in the phone book: on sorted data, check the middle and throw away the half that can't contain the target. Binary search turns that into a precise algorithm.

Keep two indices, lo and hi, marking the range that could still contain the target. Initially lo = 0 and hi = n − 1. Then repeat while lo ≤ hi:

  1. Compute the middle: mid = floor((lo + hi) / 2).
  2. If arr[mid] equals the target, return mid.
  3. If arr[mid] is less than the target, the target can only be to the right: set lo = mid + 1.
  4. Otherwise it can only be to the left: set hi = mid − 1.

If the loop ends because lo passed hi, the range is empty and the target isn't there: return −1.

The key idea is an invariant: if the target is in the array at all, it's always within arr[lo..hi]. Each step keeps that true while shrinking the range by about half. After k steps, about n / 2k elements remain, so the loop runs at most about log₂ n + 1 times: O(log n).

Two requirements are easy to forget. The data must be sorted, or discarding half is meaningless. And you need random access, the ability to jump to the middle in O(1). Arrays have it; linked lists don't, which is why binary search on a linked list gains nothing.

Binary search for 23 in a sorted array of 10 numbers: three steps, each discarding about half of the remaining range25812162338567291step 1mid=425812162338567291step 2mid=725812162338567291step 3mid=5Looking for 23: 16 < 23 go right; 56 > 23 go left; found at index 5

Step 2 of 10Practice · Put in order

Put the steps of one iteration of binary search, plus the setup, in the correct order.

Drag the items, or use the arrow buttons, to put them in order.

  1. If arr[mid] is smaller than the target, set lo to mid + 1
  2. Compute mid as the floor of (lo + hi) / 2
  3. Set lo to 0 and hi to n − 1
  4. If arr[mid] equals the target, return mid
  5. Otherwise set hi to mid − 1 and repeat while lo ≤ hi

Step 3 of 10Learn

The off-by-one minefield

Binary search is famous for being easy to understand and hard to get exactly right. Studies of professional programmers found that many couldn't write a bug-free version on the first try, and a subtle bug in a widely used standard library's binary search went unnoticed for years.

The usual suspects:

  • Loop condition: with hi = n − 1 (inclusive), the loop must run while lo ≤ hi. Using lo < hi skips checking the last remaining element.
  • Updates: setting lo = mid instead of mid + 1 can loop forever when lo and hi are adjacent, because mid keeps landing on lo.
  • Midpoint overflow: in languages with fixed-size integers, (lo + hi) can overflow for huge arrays. The safe form is lo + floor((hi − lo) / 2). JavaScript numbers don't overflow at array sizes, but it's a good habit.
  • Duplicates: the basic version returns some matching index, not necessarily the first. Finding the first occurrence needs a variant: when you find a match, record it and keep searching left.

A useful variant returns the insertion point: the index where the target would go to keep the array sorted. It's used to insert into sorted arrays and to count how many elements are less than a value.

The best defense against off-by-one bugs is to test small cases deliberately: an empty array, one element, two elements, the target at the first and last positions, and a missing target smaller than everything and larger than everything.

Step 4 of 10Practice · Code challenge

Write binarySearch(arr, target) for a sorted array of numbers. Return the index of target, or -1 if it's not present. Your loop should run O(log n) times.

Runs in a sandbox in your browser.
  • binarySearch([1, 3, 5, 7, 9, 11], 7)
  • binarySearch([1, 3, 5, 7, 9, 11], 1)
  • binarySearch([1, 3, 5, 7, 9, 11], 11)
  • binarySearch([1, 3, 5, 7, 9, 11], 4)
  • binarySearch([], 3)
  • binarySearch([42], 42)

Step 5 of 10Learn

Binary search beyond arrays

Binary search is really a general strategy: whenever a yes/no question flips from no to yes exactly once as a number increases, you can find the flip point by halving. This is sometimes called binary search on the answer.

Examples:

  • Integer square root: the largest x with x² ≤ n. As x grows, x² ≤ n is true, then false from some point on. Search the range 0 to n.
  • Minimum capacity: what's the smallest truck capacity that can ship all packages in 5 days? A capacity either works or doesn't, and if one capacity works, every larger one does too. Binary search over capacities, checking each candidate with a quick simulation.
  • Debugging with version history: if a bug appeared somewhere in the last 1,000 commits, testing the middle commit and halving finds the culprit in about 10 tests. Version control tools have a built-in command for exactly this.
  • Numerical methods: finding where a continuous function crosses zero by repeatedly halving an interval, called the bisection method.

The requirement in every case is monotonicity: once the answer becomes yes, it stays yes. The search costs O(log R) checks, where R is the size of the range of possible answers, times the cost of each check.

This is why logarithms show up so often in computer science: any time you can discard a constant fraction of the possibilities with one question, the number of questions grows only logarithmically.

Binary search on the answer: the test x squared at most 20 is true up to 4 and false from 5, so the answer is 401234567yesyesyesyesyesnononoxx² ≤ 20?The answer flips once, so halving finds the last "yes" (x = 4) in O(log n) tests

Step 6 of 10Practice · Work it out

In the worst case, about how many comparisons does binary search need on a sorted array of 1,000,000,000 elements? (230 is about 1.07 billion.)

Step 7 of 10Try the calculator

Linear vs. binary search

Enter an array size to compare the worst-case number of comparisons. Binary search needs about the floor of log₂ n plus 1.

Linear search, worst case
1,000,000 comparisons
Binary search, worst case
20 comparisons
How many times fewer
50,000

Step 8 of 10Practice · Spot the mistake

This binary search has two bugs. Tap the two lines that are wrong.

Step 9 of 10Practice · True or false

Binary search on a sorted singly linked list runs in O(log n) time, just like on a sorted array.

Step 10 of 10Practice · Choose one

A team must answer 10,000 membership queries against a list of 1,000,000 numbers that doesn't change. Which approach is most efficient overall?