Recursive search method
A recursive method is a natural match for the recursive binary search algorithm. A
method guessNumber(lowVal, highVal, scnr) has parameters that indicate the low and
high sides of the guessing range and a Scanner object for getting user input. The
method guesses at the midpoint of the range. If the user says lower, the method
calls guessNumber(lowVal, midVal, scnr). If the user says higher, the method calls
guessNumber(midVal + 1, highVal, scnr)
<[Link]>
Recursive methods can be particularly challenging to debug. Adding output
statements can be helpful. Furthermore, an additional trick is to indent the print
statements to show the current depth of recursion. The following program adds a
parameter indent to a findMatch() method that searches a sorted list for an item.
All of findMatch()'s print statements start with [Link](indentAmt
+ ...);. Indent is typically some number of spaces. main() sets indent to three
spaces. Each recursive call adds three more spaces. Note how the output now clearly
shows the recursion depth.
Figure 19.4.1: Output statements can help debug recursive methods, especially if
indented based on recursion depth.
Enter person's name: Last, First: Meeks, Stan
Find() range 0 4
Searching upper half.
Find() range 3 4
Searching upper half.
Find() range 4 4
Person not found.
Returning pos = -1.
Returning pos = -1.
Returning pos = -1.
Not found.
...
Enter person's name: Last, First: Adams, Mary
Find() range 0 4
Searching lower half.
Find() range 0 2
Searching lower half.
Find() range 0 1
Found person.
Returning pos = 0.
Returning pos = 0.
Returning pos = 0.
Found at position 0.
<[Link]>