Back to basics - Binary search

When building programs, you manipulate data; sometimes, you want to sort it; and others, you want to find something.

Searching for something in an array is very straightforward. Look at each item and compare it with the one you are looking for until you find it. It is acceptable until you start doing it many times or have to look for an item in a large amount of data.

Naïve implementation

The easiest way to find something in an array is to look over all the items. When you do this, you might get lucky and find it at the first position you look at, or if you are not, you might not find it at all, in which case you end up looking at all the data.

Doing it this way is not a problem when you have a small number of items in the array. But if you have a lot of them, the work becomes slow and inefficient.

Even finding a number in 100 elements just by looking is cumbersome.

What if we use a sorted array

But let's say we have all the information already sorted. Then, finding a number by looking is much easier for a person. Sadly computers cannot look at several items simultaneously as people do, but we can program the computer to use some hints while searching in this particular case.

Enter binary search; for this algorithm, we look at the middle of the data and determine how it compares to the item we want to find.

  • If the middle item is equal, we stop looking as no more work is needed.
  • If the item we are looking for is smaller than what is in the middle, we continue the search in the smaller values subarray (left subarray: from the first position to the mid).
  • And if the item we are looking for is bigger than the one in the middle, we continue searching in the bigger values subarray (right subarray: from middle position to the last).

What is happening is that every time you compare the item with the value at the midpoint in the subarray, you decide where to continue looking, effectively discarding half of the data.

Binary search is much faster than looking at all the data when looking for a single item, especially when it is not there. Look at the following implementation:

The find function keeps track of the subarray that is the probable place for the item and updates the first and last indexes that delimit it whenever it is needed. The result of using binary search is that instead of executing 252 instructions, only 80 got to run.

Ending notes

Binary search is an example of how using hints, plus applying common intuition, helps when writing algorithms. Every time the find function executes, it discards half of the data, quickly reducing the amount of work. Granted, you need to start with a sorted array of data, or this algorithm won't work.

This algorithm belongs to a broader classification named "Divide and Conquer" If you think about it, it is a very fitting name.


Enrique CR
All posts