Professional Documents
Culture Documents
CHAPTER SIX
RECURSION
3/2/2024 DSA- CH-6: Recursion
CH-6 Contents
2
1. Recursion basic
2. Function calls and recursive implementation
3/2/2024
CH-6 Contents
3
1. Recursion basic
2. Function calls and recursive implementation
3/2/2024
The Handshake Problem
4
3/2/2024
Recursion - Basics
5
3/2/2024
The Handshake Problem: Solution
6
3/2/2024
Examples
8
3/2/2024
CH-6 Contents
9
1. Recursion basic
2. Function calls and recursive implementation
3/2/2024
Function Call
10
Recursive Function:
A recursive function is a function that calls itself.
compute()
3/2/2024
Properties
11
3/2/2024
12
3/2/2024
Example: Handshaking Problem
13
int h(int n)
{
if (n<=2) // base case
return 1;
else
return h(n-1) + (n-1); // general case
}
3/2/2024
How do we write a recursive function?
14
3/2/2024
Three-Question Verification Method
15
3/2/2024
General Form of Recursive Functions
16
Solve(Problem)
{
if (Problem is minimal/not decomposable: a base case)
solve Problem directly; i.e., without recursion
else
{
(1) Decompose Problem into one or more similar,
strictly smaller sub-problems: SP1, SP2, ... , SPN
(2) Recursively call Solve (this method) on each
sub-problem: Solve(SP1), Solve(SP2),..., Solve(SPN)
(3) Combine the solutions to these sub-problems into a
solution that solves the original Problem
}
} 3/2/2024
Exercise:
17
3/2/2024
A factorial of a number : Solution
18
3/2/2024
Factorial of a number : Code
19
3/2/2024
20
3/2/2024
Implementation : Recursive function
21
3/2/2024
22
3/2/2024
23
3/2/2024
How to Trace Recursive Calls?
25
3/2/2024
26
3/2/2024
27
3/2/2024
Exercise
28
3/2/2024
Analysis of Recursion
29
3/2/2024
30
Time Complexity
In case of iterations, we take number of iterations to
count the time complexity.
Likewise, in case of recursion, assuming everything is
constant, we try to figure out the number of times a
recursive call is being made.
A call made to a function is Ο(1), hence the (n) number
of times a recursive call is made makes the recursive
function Ο(n).
3/2/2024
31
Space Complexity
Space complexity is counted as what amount of extra
space is required for a module to execute.
◼ Incase of iterations, the compiler hardly requires any extra
space. The compiler keeps updating the values of variables
used in the iterations.
◼ But in case of recursion, the system needs to store activation
record each time a recursive call is made.
Hence, it is considered that space complexity of
recursive function may go higher than that of a function
with iteration.
3/2/2024
Recursion vs. iteration
32
3/2/2024
When to use Recursion
33
3/2/2024
Exercise 2:
35
3/2/2024
Exercise 3:
36
Trace the following function calls and determine returned result for
each call?
void myFunction( int counter)
{
if(counter == 0)
return;
else
{
cout<<counter<<endl;
myFunction(--counter);
cout<<counter<<endl;
return;
}
}
Case: myFunction(5);
3/2/2024
Exercise 5:
38
Questions?
3/2/2024
40
Thank You
3/2/2024