07 - Recursion PDF
07 - Recursion PDF
Section 3.5
recursiveFactorial (1)
call return 1
recursiveFactorial (0)
drawTicks(length)
drawTicks( length − 1 )
drawTicks( length − 1 )
© 2010 Stallmann Programming with Recursion 6
Recursive Drawing Method
❑ The drawing method is drawTicks (3) Output
recursive definition
drawTicks (1)
drawTicks (0)
That is, an argument list consists of either (i) the empty string, (ii)
an argument, or (iii) an argument list followed by a comma and
an argument.
foo();
bar(14);
bletch(23.1, ‘a’, 14);
© 2019 Shermer Programming with Recursion 10
Example of Linear Recursion
Algorithm LinearSum(A, n): Example recursion trace:
Input:
A integer array A and an integer call return 15 + A[4] = 15 + 5 = 20
n = 1, such that A has at least LinearSum(A,5)
n elements call return 13 + A[3] = 13 + 2 = 15
Output: LinearSum (A,4)
The sum of the first n integers call return 7 + A[2] = 7 + 6 = 13
in A LinearSum (A,3)
if n = 1 then call return 4 + A[1] = 4 + 3 = 7
return A[0] LinearSum (A,2)
else call return A[0] = 4
© 2010 Goodrich,
Using Recursion 11
Tamassia
Reversing an Array
Algorithm ReverseArray(A, i, j):
Input: An array A and nonnegative integer
indices i and j
Output: The reversal of the elements in A
starting at index i and ending at j
if i < j then
Swap A[i] and A[ j]
ReverseArray(A, i + 1, j - 1)
return
❑ Example trace:
0, 8
0, 4 4, 4
0, 2 2, 2 4, 2 6, 2
0, 1 1, 1 2, 1 3, 1 4, 1 5, 1 6, 1 7, 1
Example
cbb + ba = abc a,b,c stand for 7,8,9; not
799 + 98 = 997 necessarily in that order
[] {a,b,c}
Initial call
PuzzleSolve (3,(),{a,b,c})