Binary Search: Private Boolean Int Int Int
Binary Search: Private Boolean Int Int Int
Do you remember the binary search in Chapter 11? Here is the description of the algorithm: “The
algorithm divides the list in half (divides by 2—that’s why it’s called a binary search) and decides
which half to look in next. Division of the selected portion of the list is repeated until the item is
found or it is determined that the item is not in the list.” There is something inherently recursive
about this description.
The solution is expressed in terms of smaller versions of the original problem: If the answer isn’t
found in the middle position, perform a binary search (a recursive call) to search the appropriate
half of the list (a smaller problem). In the iterative version, we kept track of the bounds of the current
search area with two local variables, first and last. In the recursive version, we call the method with
these two values as arguments. We must call the recursive binary search method from the isThere
method of the SortedList class rather than writing it as part of that method.
private boolean binIsThere(int first, int last, int item)
// Returns true if item is in the list
{
if (first > last) // Base case 1
return false;
else
{
int midPoint;
midPoint = (first + last) / 2;
if (item < listItems[midPoint])
return binIsThere(first, midPoint-1, item);
else if (item == listItems[midPoint])
return true; // Base case 2
else
return binIsThere(midPoint+1, last, item);
}
}