We can draw a recursion trace, where we have a box for each recursive call, an arrow from each caller to callee and an arrow from each callee to caller showing return value.
Base case: values of the input variables for which we perform no recursive calls are called base cases (there should be at least one base case and every possible chain of recursive calls must eventually reach a base case)
Algorithm: LinearSum(A, n)Input: An integer array A and an integer n≥1, such that A has at least n elements.
Output: The sum of the first n integers in A.
if n = 1 then return A[0]else return LinearSum(A, n-1) + A[n-1]
Example recursion trace over A={4,3,6,2,5} and n=5:
Algorithm: ReverseArray(A, i, j)Input: An array A and non-negative 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
Defining Arguments for Recursion
In specifying a recursive method, it is important to define the method in a way that facilities recursion. This sometimes requires we define additional parameters that are passed to the method.
For example, even if we only want to reverse whole arrays, we still define the array reversal method as ReverseArray(A, i, j), not ReverseArray(A).
Computing Powers
The power function, p(x,n)=xn can be defined recursively as:
p(x,n)={1x⋅p(x,n−1)if n=0else
This leads to a power function that runs in time linear in n since we make n recursive calls and n multiplications. But we can go faster than this by using recursive squaring:
p(x,n)=⎩⎨⎧1,(p(x,2n))2,x⋅(p(x,2n−1)2,if n=0if n>0 is evenif n>0 is odd
if n == 0 then return 1if n is even then y = Power(x, x / n) return y * yelse y = Power(x, (n - 1) / 2) return x * y * y
Tail Recursion
Tail Recursion
Tail recursion occurs when a linearly recursive method makes its recursive call as its last step. The array-reversal method is an example. Such methods can easily be converted to non-recursive methods, to save on resources.
For example, add all numbers in an integer array A:
Algorithm: BinarySum(A, i, n)Input: An array A and integers i≥0 and n≥1Output: The sum of the n integers in A starting a index i
if n = 1 then return A[i]return BinarySum(A, i, ceil(n / 2)) + BinarySum(A, i + ceil(n / 2), floor(n / 2))