Data Structures
UNIT-1
Recursion: Introduction, format of recursive
functions, recursion Vs. Iteration,
Examples
Recursio
• n itself is a recursive.
A function which calls
• Recursion solves a task by calling itself.
• Ensure recursion should terminate at some condition.
• Recursion uses stack memory to execute.
• Why recursion is needed?
Recursion reduces the code
There are some problems which are difficult with
iterative method can be solved with recursive
method.
example: Towers of Hanoi, Binary search, Divide
and Conquer problems.
Format of Recursive Functions
• Recursive solution for problem involves a 2-way
journey. First, we decompose the problem from top to
bottom and then we solve it from bottom to top.
• Recursive function has two cases:
Base case : It solves the problem. here
recursion calling should terminate.
Recursive case or General case: function calls
itself to perform a sub task. It contains the
logic to reduce the problem size.
Example
• Recursive function to find factorial of a given number
is
n!=1, if n=0 //base
case n!=n*(n-1)!, if n>0 //
recursive case
int factorial(int number)
{
if(number==0) // base case
return 1;
else
return number*factorial(number-1); //
recursive case
or general case
}//factorial()
Let, number=4
factorial(4) returns 24 to main because
Main calls main is calling function to factorial(n)
factorial(4
)
factorial (4) =4*factorial (3) Returns 6
Calls factorial(3) factorial (4)
factorial (3) =3*factorial (2) =4*6=24
Calls factorial(2)
Returns 2
factorial (2) =2*factorial (1) factorial (3) =3*2=6
Calls factorial(1)
Returns 1
factorial (1) =1*factorial (0) factorial (2)
=2*1=2
Calls factorial(0)
factorial (0) =1 Returns
1
Differences between recursive and iterative methods
Recursive method Iterative method
Reduces the code Length of the code is more
Speed of recursive methods are Faster
slow
terminated when it reaches base terminated when the condition is
condition false
Each recursive call requires extra does not require any extra space
space to execute. Stack memory
is required
If recursion goes into infinite , the Goes to infinite loop
program runs out of memory and
results in stack overflow
solution to some problems are solution to problem may not
easier with recursion always easy
Examples of recursion
1. Factorial of a number
2. Fibonacci series
3. Tree traversals- Preorder, Inorder, Postorder.
4. Binary search
5. Merge sort
6. Quick sort
7. Towers of Hanoi
8. Divide and conquer problems
9. Dynamic programming