Chapter 12: Recursion 237
Recursive Binary Search
The binary search algorithm from Chapter 9 is a very efficient algorithm for searching an ordered list. The
algorithm (in pseudocode) is as follows:
highIndex – the maximum index of the part of the list being searched
lowIndex – the minimum index of the part of the list being searched
target — the item being searched for
//look in the middle
else
search the second half of the list
Notice the recursive nature of the algorithm. It is easily implemented recursively. Note that three parameters are
needed—the target and the indices of the first and last elements in the part of the list to be searched. To “search
the first half of the list” the algorithm must be called with the high and low index parameters representing the
first half of the list. Similarly, to search the second half the algorithm must be called with the high and low
index parameters representing the second half of the list. The file IntegerListB.java contains a class representing
a list of integers (the same class that has been used in a few other labs); the file IntegerListBTest.java contains a
simple menu-driven test program that lets the user create, sort, and print a list and search for an item in the list
using a linear search or a binary search. Your job is to complete the binary search algorithm (method
binarySearchR). The basic algorithm is given above but it leaves out one thing: what happens if the target is not
in the list? What condition will let the program know that the target has not been found? If the low and high
indices are changed each time so that the middle item is NOT examined again (see the diagram of indices
below) then the list is guaranteed to shrink each time and the indices “cross”—that is, the high index becomes
less than the low index. That is the condition that indicates the target was not found.
lo middle high
Fill in the blanks below, then type your code in. Remember when you test the search to first sort the list.
private int binarySearchR (int target, int lo, int hi)
{
int index;
index = mid;
else if (target < list[mid])
// fill in the recursive call to search the first half