Let's see an example. Say we're searching for the value 37 in the following array:

Figure %: Array on which to perform a binary search

We set our low and our high values to be at the beginning and ends of the array, and our middle value to be their average:

Figure %: Set initial first, middle and last values

We then compare 37 to the value at the middle location. Is 37 = = 45? No, it is less than 45. So we update the last pointer to be middle - 1, and readjust the middle pointer accordingly:

Figure %: Now searching the bottom half

Is 37 = = 35? No. It is greater than 35. So we update the first and middle pointers accordingly:

Figure %: Now searching upper half of bottom half

Is 37 == 37? Yes! We found it:

Figure %: We found it!

Recursive implementation

For those of you who have studied recursion, you might notice that binary search fits the model for a function easily implemented recursively (in fact, the algorithm gets its name from the repeated halving of the data set). Let's see how we can implement this function recursively.