Programming and Problem Solving with Java

(やまだぃちぅ) #1
13.3 Recursive Algorithms with Structured Variables | 649

element to be printed is beyond the index of the last element in the array. Therefore, we
must pass the index of the last array element as an argument. We call the indexes firstand
last. When firstis greater than last, we are finished. The name of the array is data.


public static voidprint(
int[] data, // Array to be printed
int first, // Index of first element
int last ) // Index of last element
// Prints an array
{
if (first <= last)
{ // Recursive case
outFile.println(data[first]+ " ");
printArray(data, first + 1, last);
}
// Empty else clause is the base case
}


Here is a code walk-through of the method call

print(data, 0, 4);


using the pictured array.


Call 1:firstis 0 and lastis 4. Because firstis less than last, the value in data[first]
(which is 23) is printed. Execution of this call pauses while the array from first+ 1 through
lastis printed.
Call 2:firstis 1 and lastis 4. Because firstis less than last, the value in data[first]
(which is 44) is printed. Execution of this call pauses while the array from first+ 1 through
lastis printed.
Call 3:firstis 2 and lastis 4. Because firstis less than last, the value in data[first]
(which is 52) is printed. Execution of this call pauses while the array from first+ 1 through
lastis printed.
Call 4:firstis 3 and lastis 4. Because firstis less than last, the value in data[first]
(which is 61) is printed. Execution of this call pauses while the array from first+ 1 through
lastis printed.
Call 5:firstis 4 and lastis 4. Because firstis equal to last, the value in data[first]
(which is 77) is printed. Execution of this call pauses while the array from first+ 1 through
lastis printed.


[ 0 ] 23
[ 1 ] 44
[ 2 ] 52
[ 3 ] 61
[ 4 ] 77

data
Free download pdf