10.5. Binary Searching

Binary search is an improvement over linear searching that works only if the data in the array are sorted beforehand.

Suppose we have the following array data, showing indices underneath:

10   20   30   40   50   60   70   80   90   100  115  125  135  145  155  178  198
 0    1    2    3    4    5    6    7    8     9   10   11   12   13   14   15   16

If we are looking for a number, say, 115, here is a visual on how we might go about it:

10   20   30   40   50   60   70   80   90   100  115  125  135  146  155  178  198
min=0 max=16 mid=8: 90 < 115
                                             100  115  125  135  146  155  178  198
min=9 max=16 mid=12: 135 > 115
                                             100  115  125
min=9 max=11 mid=10: found 115

Binary search works by keeping track of the midpoint (mid) and the minimum (min) and maximum (max) positions where the item might be.

Let’s see how we might search for the value 115.

  • We start by testing the data at position 8. 115 is greater than the value at position 8 (100), so we assume that the value must be somewhere between positions 9 and 16.
  • In the second pass, we test the data at position 12 (the midpoint between 9 and 16). 115 is less than the value at position 12, so we assume that the value must be somewhere between positions 9 and 11.
  • In the last pass, we test the value at position 10. The value 115 is at this position, so we’re done.

So binary search (as its name might suggest) works by dividing the interval to be searched during each pass in half. If you think about how it’s working here with 16 items. Because there is integer division here, the interval will not always be precisely half. it is the floor of dividing by 2 (integer division, that is).

You can see that the above determined the item within 3 steps. At most it would be 4 steps, which is \(log_2 16 = 4\).

Table Of Contents

Previous topic

10.4. Sorting Algorithms

Next topic

10.6. Lab: Arrays

This Page