Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^650) | Recursion
Call 6:firstis 5 and lastis 4. Because firstis greater than last, the execution
of this call is complete. Control returns to the preceding call.
Call 5:Execution of this call is complete. Control returns to the preceding call.
Calls 4, 3, 2, and 1:Each execution is completed in turn, and control returns to
the preceding call.
Notice that once the deepest call (the call with the highest number) was reached,
each of the calls before it returned without doing anything. When no statements
execute after the return from the recursive call to the method, the recursion is known
as tail recursion.Tail recursion often indicates that we could solve the problem more easily us-
ing iteration. We used a recursive solution in the array example because it made the recursive
process easy to visualize; in practice, an array should be printed iteratively.
Figure 13.4 shows the execution of the printmethod with the values of the parameters
for each call. Notice that the array becomes smaller with each recursive call (data[first]
Tail recursion A recursive al-
gorithm in which no statements
execute after the return from
the recursive call
Call 1:
Call 2:
Call 3:
Call 4:
Call 5:
Call 6:
first
0
last
4
first
1
last
4
first
2
last
4
first
3
last
4
first
4
last
4
first
5
last
4
data[ 0 ]
is
printed.
data[ 1 ]
is
printed.
data[ 2 ]
is
printed.
data[ 3 ]
is
printed.
data[ 4 ]
is
printed.
print(data, 0 , 4 )
data, which is the array, is not shown in the boxes.
Figure 13.4 Execution of print(data, 0 , 4 )
T
E
A
M
F
L
Y
Team-Fly®

Free download pdf