6 - Recursion 1
6 - Recursion 1
Review of
Recursion
How
SLIDE 3 to write repetitive
Two
algorithms?
Approaches: Recursion is a
repetitive process
in which an
algorithm calls
itself.
Iteration
Recursion
Recursion:
SLIDE 3 What is it?
Case Study: Factorial Algorithm.
Each call must reduce the size of the problem and move it
toward the base case.
The base case, when reached, must terminate without a call to
the recursive algorithms; that is, it must execute a return.
DESIGN
IMPLEMENTATION.
DESIGN
IMPLEMENTATION.
Recursive calls (reads)
LIMITATIONS OF RECURSION.
Do not use recursion if answer is NO to any question
below:
1. Is the algorithm or data structure naturally suited to
recursion?
2. Is the recursive solution shorter and more
understandable?
3. Does the recursive solution run within acceptable time
and space limits?
SOME MORE
EXAMPLES.
Greatest Common Divisor
Fibonacci Numbers
Prefix to Postfix Conversion
The Towers of Hanoi
SOME MORE RECURSIVE EXAMPLES: GCD.
Note:-Recursive solution to calculate Fibonacci no.s is not efficient for large numbers .
SOME MORE RECURSIVE EXAMPLES: PREFIX TO
POSTFIX CONVERSION
The legend said that when all 64 disks had been transferred to the destination
needle, the stars would be extinguished and the world would end.
The monks moved one disk to another needle each hour, subject to the
following rules:
1. Only one disk could be moved at a time.
2. A larger disk must never be stacked above a smaller one.
3. One and only one auxiliary needle could be used for the intermediate
storage of disks.
This problem is interesting for two reasons.
1. Recursive solution is much easier to code than the iterative solution would be, as is
often the case with good recursive solutions.
2. It’s solution pattern is different from the simple examples we have been discussing
RECURSIVE TOWERS OF HANOI: DESIGN.
int fib(int n)
{
if(n==0)
return 0;
if(n==1)
return 1;
else
{
return (fib(n-1) + fib(n-2));
}
}
Recursive program to do a binary search
int binary(int item, int a[], int low, int high)
{
int mid;
if(low > high)
return -1;
mid=(low+high)/2;
if(item==a[mid])
return mid;
else if(item<a[mid])
{
high=mid-1;
return binary(item, a, low, high);
}
else
{
low=mid+1;
return binary(item, a, low, high);
}
}
C program for tower of hanoi problem
The End.
OF RECURSION.