Recursion: Compiled By: Dr. Mohammad Omar Alhawarat
Recursion: Compiled By: Dr. Mohammad Omar Alhawarat
number
37
What Is Recursion?
4
m1 m2 m3
m1 m2 m3
m1 m2 m3
Phases of Recursion
10
Forward Phase:
Every recursion has a forward phase in which a call at
every level, except the last, spins off a call to the next
level, and waits for the latter call to return control it.
Backward Phase:
Every recursion has a backtracking phase in which a call
at every level, except the first, passes control back to the
previous level, at which point the call waiting at the
previous level wakes up and resumes its work.
Examples: Simple problems
11
Summation
Factorial
Fibonacci
Summation
12
N N 1
i N i
i 1 i 1
N 2
N N 1 i
i 1
N 3
N N 1 N 2 i
i 1
N N 1 N 2 2 1
The sum of 1 to N, defined recursively
13
return result;
}
Recursive calls to the sum method
14
result = 4 + sum(3)
main
result = 2 + sum(1)
sum(3)
sum
sum(2) result = 1
sum
sum(1)
sum
Factorial
15
N is 1 x 2 x 3 x ... x N – 1 x N
Computing the Factorial
17
0, if n == 0 base case
fibn = 1, if n == 1 base case
fibn – 1 + fibn – 2, if n > 1 recursive case
Fibonacci Sequence
20
int fibo(int n)
{
if (n < 2)
return 1;
else
return fibo(n-1) + fibo(n-2);
}
Avoiding Recursion
24
Avoiding Recursion
25
int fibo(int n)
{
int[] f = new int[n];
f[0]=0;
f[1]=1;
return f[n];
}
A Simple Solution to a Difficult Problem
26
26
Towers of Hanoi: An Application
27
35
Recursion vs. Iteration
36
Comparison of elements of a
loop and a recursive function