Recursion Basics
1Introduction
This lecture explains a recursive algorithm as a method that constructs the result for an input from the result for a smaller input of the same kind. It defines the base case, recursive step, and termination measure needed for the design, and proves termination and correctness separately. It also explains the execution process through the call stack and analyzes its complexity.
2Components of a Recursive Algorithm
A
A
A
3Recursive Definition of Factorial
For , factorial is defined by
The specification of is: given , return . A recursive algorithm satisfying this specification is
fact(n):
if n = 0:
return 1
return n * fact(n - 1)
The condition is the base case, and the computation of for is the recursive step. We choose as the termination measure.
4Termination
If , the algorithm terminates without a recursive call. If , the recursive call receives , and
Thus, the nonnegative-integer termination measure strictly decreases in every recursive call. A strictly decreasing sequence of nonnegative integers cannot be infinite, so the computation reaches after finitely many calls. Therefore, terminates for every .
5Correctness
Termination guarantees that the computation ends, but it does not by itself guarantee that the return value satisfies the specification. We prove the latter claim by induction on .
- Base case: for , the algorithm returns . Since , the return value is correct.
- Inductive step: let and assume . The algorithm returns . By the inductive hypothesis and the definition of factorial,
Therefore, for every . The base case and recursive step correspond respectively to the base case and inductive step of the proof.
6Call Stack
A
During the evaluation of , frames for , , , and are pushed in that order. After the base case returns , the calls return in reverse order and construct , , and . Consequently, the recursive-call depth determines the number of frames stored simultaneously.
7Complexity
We use the
In this model, for each input with , makes one recursive call and performs a constant-time multiplication. Its time complexity satisfies
so . The maximum call depth is . Because each frame uses a constant amount of storage, the auxiliary-space complexity of the call stack is .
8Design and Verification Procedure
- State the specification of the input and return value.
- Define a base case that requires no recursive call.
- Define a recursive step that constructs the result from a smaller input of the same kind.
- Provide a termination measure that strictly decreases in every recursive call, and prove termination.
- Prove correctness, for example by induction.
- Evaluate time and space complexity from the number of recursive calls and the maximum call depth.