Lec 4 Algo Spr15 Recursion
Lec 4 Algo Spr15 Recursion
Spring 2015
Recursion
Basic problem solving technique is to
divide a problem into smaller subproblems
These subproblems may also be divided
into smaller subproblems
When the subproblems are small enough
to solve directly the process stops
A recursive algorithm is a problem solution
that has been expressed in terms of two or
more easier to solve subproblems
Recursion
Recursion occurs when a function/procedure calls itself.
Many algorithms can be best described in terms of recursion.
Example: Factorial function
The product of the positive integers from 1 to n inclusive is
called "n factorial", usually denoted by n!:
n! = 1 * 2 * 3 .... (n-2) * (n-1) * n
Recursive Definition
of the Factorial Function
n! =
5! = 5 * 4!
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1 * 0!
1,
n * (n-1)!
= 5 * 24 = 120
= 4 * 3! = 4 * 6 = 24
= 3 * 2! = 3 * 2 = 6
= 2 * 1! = 2 * 1 = 2
= 1 * 0! = 1
if n = 0
if n > 0
Recursive Definition
of the Fibonacci Numbers
The Fibonacci numbers are a series of numbers as follows:
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
...
fib(n) =
1,
n <= 2
fib(n-1) + fib(n-2), n > 2
fib(3) = 1 + 1 = 2
fib(4) = 2 + 1 = 3
fib(5) = 2 + 3 = 5
Recursive Definition
int BadFactorial(n){
int x = BadFactorial(n-1);
if (n == 1)
return 1;
else
return n*x;
}
Counting Digits
Recursive definition
digits(n) = 1
1 + digits(n/10)
if (9 <= n <= 9)
otherwise
Example
digits(321) =
1 + digits(321/10) = 1 +digits(32) =
1 + [1 + digits(32/10)] = 1 + [1 + digits(3)] =
1 + [1 + (1)] =
3
Disadvantages
May run slower.
Compilers
Inefficient Code
Advantages
More natural.
Easier to prove correct.
Easier to analyze.
More flexible.
Reference
Introduction to Algorithms
Chapter # 4
Thomas H. Cormen
3rd Edition