0% found this document useful (0 votes)
16 views54 pages

6 - Recursion 1

The document provides an overview of recursion, explaining its definition, advantages, and limitations. It includes case studies such as the factorial algorithm, Fibonacci numbers, and the Towers of Hanoi, illustrating how recursive algorithms can simplify problem-solving. Additionally, it presents examples of recursive implementations in programming, highlighting the differences between recursion and iteration.

Uploaded by

xiy29440
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views54 pages

6 - Recursion 1

The document provides an overview of recursion, explaining its definition, advantages, and limitations. It includes case studies such as the factorial algorithm, Fibonacci numbers, and the Towers of Hanoi, illustrating how recursive algorithms can simplify problem-solving. Additionally, it presents examples of recursive implementations in programming, highlighting the differences between recursion and iteration.

Uploaded by

xiy29440
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

SLIDE 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.

1. Iterative Defi nition and Solution


2. Recursive Defi nition
3. Recursive Solution
Factorial:
SLIDE 3 Iterative Definition.
The defi nition involves only the algorithm
parameter(s) and not the algorithm itself.
Factorial:
SLIDE 3 Recursive Definition.
A repetitive algorithm uses recursion
whenever the algorithm appears within
the defi nition itself.
Factorial:
SLIDE 3 Recursive Definition.
BE SAFE
Iterative Solution
SLIDE 4
BE SAFE
Recursive Solution
SLIDE 4
WHICH CODE IS SIMPLER?

Which one does not have a loop?


Recursive
SLIDE 4 Solution
Analysis

Figure 2-4 traces the


recursion and the
parameters for each
individual call.
Designing
SLIDE 3 Recursive
Algorithms.
Analytic Approach:
1. The Design Methodology
2. Limitations of Recursion
3. Design Implementation
THE DESIGN METHODOLOGY.

Every recursive call either solves a part of the problem or it


reduce the size of the problem.
 Base case
 The statement that “solves” the problem.
 Every recursive algorithm must have a base case.
 General case
 The rest of the algorithm
 Contains the logic needed to reduce the size of the problem.
COMBINE THE BASE CASE AND THE
GENERAL CASES INTO AN ALGORITHM
Rules for designing a recursive algorithm:
1. First, determine the base case.
2. Then determine the general case.
3. Combine the base case and the general cases into an
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.

We use the Euclidean algorithm to determine the greatest common


divisor between two nonnegative integers.

Given two integers, a and b, the greatest common divisor is


recursively found using the formula given above.
SOME MORE RECURSIVE EXAMPLES: GCD.
GCD
IMPLEMENTATION.
SOME MORE RECURSIVE EXAMPLES: FIBONACCI
NUMBERS

Fibonacci numbers are named after Leonardo Fibonacci, an Italian


mathematician who lived in the early thirteenth century. In this series
each number is the sum of the previous two numbers. The first few
numbers in the Fibonacci series are:
FIBONACCI SERIES: DESIGN.
FIBONACCI NUMBERS
IMPLEMENTATION.
FIBONACCI NUMBERS IMPLEMENTATION CALLS.

Note:-Recursive solution to calculate Fibonacci no.s is not efficient for large numbers .
SOME MORE RECURSIVE EXAMPLES: PREFIX TO
POSTFIX CONVERSION

An arithmetic expression can be


represented in three different formats:
1. Infix
2. Postfix
3. Prefix

1. Prefix notation: Operator comes before the


operands.
2. Infix notation: Operator comes between the
SOME MORE RECURSIVE EXAMPLES:
THE TOWERS OF HANOI

According to the legend, the monks in a remote mountain monastery


knew how to predict when the world would end.
SOME MORE RECURSIVE EXAMPLES:
THE TOWERS OF HANOI
They had a set of three diamond needles. Stacked on the first diamond needle
were 64 gold disks of decreasing size.

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.

Today, we know we need to have moves to move all the disks.


RECURSIVE TOWERS OF HANOI: RULES.
Case: Hanoi Towers

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.

CASE 1: ONE DISK

Move one disk from source to destination needle


RECURSIVE TOWERS OF HANOI: DESIGN.

CASE 1: TWO DISKS

1. Move one disk to auxiliary


needle.
2. Move one disk to destination
needle
3. Move one disk from auxiliary
to destination needle.
RECURSIVE TOWERS OF HANOI: DESIGN.

CASE 3: THREE DISKS

1. Move n –1 disks from source to auxiliary. General case

2. Move one disk from source to destination. Base case

3. Move n –1 disks from auxiliary to destination.


General case
Algorithm:
Towers of
Hanoi.
Algorithm:
Towers of
Hanoi

1. Move n –1 disks from source to


auxiliary.
2. Move one disk from source to
destination.
3. Move n –1 disks from auxiliary
to destination.
Algorithm:
Towers of
Hanoi

1. Move n –1 disks from source to


auxiliary.
2. Move one disk from source to
destination.
3. Move n –1 disks from auxiliary
to destination.
RECURSIVE TOWERS OF
HANOI: DESIGN. CASE 3: THREE DISKS
Iteration Recursion
Uses loops uses if-else and repetitive function calls

Counter controlled and body Terminates when base condition


of loop terminates when the is reached.
termination condition fails.

Execution is faster and takes Consumes time and space


less space. because of push and pop.

Difficult to design for some Best suited for some problems


problems. and easy to design.
Advantages of Recursion
1. Clearer and simpler versions of algorithms can be created using recursion.
2. Recursive definition of a problem can be easily translated into a recursive
function.
3. Lot of bookkeeping activities such as initialization etc required in iterative
solution is avoided.
Disadvantages
4. When a function is called, the function saves formal parameters, local variables
and return address and hence consumes a lot of memory.
5. Lot of time is spent in pushing and popping and hence consumes more time to
compute result.
Recursive chains
 Recursive function need not call itself directly. It can call itself indirectly
as shown
A(parameters) B(parameters)
{ {
. . ……….. …………
………….. …………
B(arguments) A(arguments)
} }
Recursive program for multiplying 2 numbers

int mul(int m, int n) {


int y;
if(m==0 || n==0)
return 0;
if(n==1)
return m;
else{
y=mul(m, n-1);
return(y+m);
}
Recursive program to find the nth fibonacci number

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

void tower (int n, char source, char temp, char destination) {


if(n==1) {
cout<<“move disk 1 from “<<source<<“ to “<<destination<<endl;
return;
}

/*moving n-1 disks from A to B using C as auxiliary*/


tower(n-1, source, destination, temp);

cout<<“move disk “<<n<<“ from “<<source<<“ to


“<<destination<<endl;

/*moving n-1 disks from B to C using A as auxiliary*/


tower(n-1, temp, source, destination);
}
LENGTH OF A STRING USING RECURSION

int StrLen(str[], int index)


{
if (str[index] == '\0') return 0;

return (1 + StrLen(str, index + 1));


}
LENGTH OF A STRING USING RECURSION
USING STATIC VARIABLE
int StrLen(char *str)
{
static int length=0;
if(*str != ‘\0’)
{
length++;
StrLen(++str);
}
return length;
TO CHECK WHETHER A GIVEN STRING IS
PALINDROME OR NOT USING RECURSION
int isPalindrome(char *inputString, int leftIndex, int rightIndex) {
/* Recursion termination condition */
if(leftIndex >= rightIndex) return 1;
if(inputString[leftIndex] == inputString[rightIndex]){
return isPalindrome(inputString, leftIndex + 1, rightIndex - 1);
}
return 0;
}
int main(){
char inputString[100];
printf("Enter a string for palindrome check\n");
scanf("%s", inputString);
if(isPalindrome(inputString, 0, strlen(inputString) - 1))
printf("%s is a Palindrome \n", inputString);
else
printf("%s is not a Palindrome \n", inputString);
getch();
return 0;
}
TO COPY ONE STRING TO ANOTHER
USING RECURSION

void copy(char str1[], char str2[], int index)


{
str2[index] = str1[index];
if (str1[index] == '\0') return;
copy(str1, str2, index + 1);
}
Exercise
SLIDE 6

The End.
OF RECURSION.

You might also like