Recursion
What is recursion?
In recursion, the solution to problem is defined as a combination of:
- A solution to a simpler version of the problem
- The solution to an elementary case of the problem
An example of recursion
Let's define a function Power(n):
- If n = 1, the result is 1
- otherwise, the result is n times Power(n - 1)
An example of double recursion
Let's define a function Fibonacci(n):
- If n = 1 or n = 2, the result is 1
- otherwise, the result is Fibonacci(n - 2) + Fibonacci(n - 1)
Tower of Hanoi as a double recursion
Let's define a procedure TowerOfHanoi(NumberOfDisks, OriginPeg, DestinationPeg,
AuxiliaryPeg):
- If NumberOfDisks = 1, move a disk from OriginPeg to DestinationPeg
- otherwise,
- TowerOfHanoi(NumberOfDisks - 1, OriginPeg, AuxiliaryPeg, DestinationPeg)
- Move a disk from OriginPeg to DestinationPeg
- TowerOfHanoi(NumberOfDisks - 1, AuxiliaryPeg, DestinationPeg, OriginPeg)