Sorting and searching · Exercise 57 of 100

Binary search

In an array sorted from smallest to largest, compare the target with the middle value of the current range. If they differ, the sorted order tells you which half to keep, and you can skip the middle value on the next check. Stop when you find the target or the range is empty.

Try it yourself

Search for 25 in [3, 6, 6, 10, 14, 19, 25, 31]. Starting with the whole array and choosing the lower middle position whenever there are two, how many middle values do you check, including the match?

One-step hint

Bracket the current search range. Tally each lower-middle value you inspect, and move the appropriate bracket past it if the search continues.

Worked solution
  1. The lower middle value is 10. Since 25 is larger, keep [14, 19, 25, 31].
  2. The next check finds 19, so keep [25, 31]. Its lower middle value is 25, making the match the third check.
DSA compiler

Explore the idea visually in the binary search lab.