0% found this document useful (0 votes)
61 views40 pages

DSA Chapter 6

The document discusses recursion, including recursive functions, recursive calls, base cases, and general cases. Recursion involves solving a problem by solving smaller instances of the same problem until a base case is reached. Examples of recursive functions for calculating factorials and powers are provided.

Uploaded by

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

DSA Chapter 6

The document discusses recursion, including recursive functions, recursive calls, base cases, and general cases. Recursion involves solving a problem by solving smaller instances of the same problem until a base case is reached. Examples of recursive functions for calculating factorials and powers are provided.

Uploaded by

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

1

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

 There are n people in a room. If each person


shakes hands once with every other person. What
is the total number h(n) of handshakes?

3/2/2024
Recursion - Basics
5

 Sometimes, the best way to solve a problem is by


solving a smaller version of the exact same
problem first.
 Recursion is a technique that solves a problem by
solving a smaller problem of the same type.
 Insome problems, it may be natural to define the
problem in terms of the problem itself.
 Recursion is useful for problems that can be
represented by a simpler version of the same
problem.

3/2/2024
The Handshake Problem: Solution
6

 There are n people in a room. If each person


shakes hands once with every other person. What
is the total number h(n) of handshakes?
h(n) = h(n-1) + n-1 h(4) = h(3) + 3 h(3) = h(2) + 2 h(2) = 1

h(n): Sum of integer from 1 to n-1 = n(n-1)


3/2/2024 / 2
Recursive Function
7

 When you turn this into a program, you end up with


functions that call themselves.
 Some computer programming languages allow a
module or function to call itself.
 This technique is known as recursion.

 In recursion, a function A either calls itself directly


or calls a function B that in turn calls the original
function A.
 The function A is called recursive function.

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

 So far, we have seen methods that call other


functions.
 For example, the main() function calls the square()
function.
main()
square()

 Recursive Function:
A recursive function is a function that calls itself.

compute()
3/2/2024
Properties
11

 There are two properties that a recursive function


must have −
1. Base criteria − There must be at least one base
criteria or condition, such that, when this condition is
met the function stops calling itself recursively.
◼ Base case: a simple case of the problem that can be
answered directly; does not use recursion.

3/2/2024
12

2. Progressive approach − The recursive calls should


progress in such a way that each time a recursive call
is made it comes closer to the base criteria.
◼ Recursive case (General case): a more complicated case
of the problem, that isn't easy to answer directly, but can
be expressed elegantly with recursion; makes a recursive
call to help compute the overall answer.

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

 Determine the following important information


 The size factor
◼ E.g. n in factorial(n)
 The base case(s)
◼ The one for which you know the answer
 The general case(s):
◼ The one where the problem is expressed as a smaller
version of itself
 Verify the algorithm
 Use the "Three-Question-Method"

3/2/2024
Three-Question Verification Method
15

 The Base-Case Question:


 Is there a non-recursive way out of the function, and
does the routine work correctly for this "base" case?
 The Smaller-Caller Question:
 Does each recursive call to the function involve a
smaller case of the original problem, leading
inescapably to the base case?
 The General-Case Question:
 Assuming that the recursive call(s) work correctly,
does the whole function work correctly?

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

 Write a recursive functions for the following


problems?
 Determine the base case and general case?
1. A factorial of a number
2. A power of a number

3/2/2024
A factorial of a number : Solution
18

 The base case : n! = 1 if n=0


 The general case: n!= (n-1)! * n if n>0

3/2/2024
Factorial of a number : Code
19

3/2/2024
20

3/2/2024
Implementation : Recursive function
21

 Many programming languages implement recursion


by means of stacks.
 Generally, whenever a function (caller) calls another
function (callee) or itself as callee, the caller
function transfers execution control to the callee.
 Thistransfer process may also involve some data to be
passed from the caller to the callee.
 This implies, the caller function has to suspend its
execution temporarily and resume later when the
execution control returns from the callee function.

3/2/2024
22

 Here, the caller function needs to start exactly from


the point of execution where it puts itself on hold.
 It
also needs the exact same data values it was
working on.
 For this purpose, an activation record (or stack
frame) is created for the caller function.

3/2/2024
23

 This activation record keeps the information about local


variables, formal parameters, return address and all
information passed to the caller function.
3/2/2024
Example: Activation record
24

3/2/2024
How to Trace Recursive Calls?
25

 When a function is called recursively, each call gets a


fresh copy of all local/automatic variables.
 And every call is saved in a stack, where the last most call
will be processed first.
 Every program maintains a stack (a special area of
memory) during run time to remember where to go
back when a function is called.
 You can trace a recursive function by pushing every call
it makes to a stack and then come to the previous call
when it returns. Look at the following piece of code and
try to trace it;

3/2/2024
26

3/2/2024
27

3/2/2024
Exercise
28

 Trace the following function calls and determine


returned result for each call?

3/2/2024
Analysis of Recursion
29

 One may argue why to use recursion, as the same


task can be done with iteration.
 Recursionmakes a program more readable and uses
fewer line of code.
 Time Complexity
 Space Complexity

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

 Iteration can be used in place of recursion


 An iterative algorithm uses a looping construct
 A recursive algorithm uses a branching structure

 Recursive solutions are often less efficient, in terms


of both time and space, than iterative solutions
 Recursion can simplify the solution of a problem,
often resulting in shorter, more easily understood
source code

3/2/2024
When to use Recursion
33

 The main two factors to consider are:


 Efficiency
 Clarity
◼ Recursive methods are less efficient in time and space.
◼ Recursive methods are easier to write and to
understand
 It is Good to use recursion when:
1. Relatively shallow
2. Same amount of work as the non-recursive version
3. Shorter and simpler than the non-recursive solution
3/2/2024
Exercise 1:
34

 Trace the following function calls and determine


returned result for each call? Case: print(5);

3/2/2024
Exercise 2:
35

 Trace the following function calls and determine


returned result for each call? Case: print(5);

3/2/2024
Exercise 3:
36

 Trace the following function calls and determine


returned result for each call?
bool isPrime(int p, int i)
{
if (i==p) return 1;
if (p%i == 0) return 0;
return isPrime (p, i+1);
}
Case: isPrime(5,2);
3/2/2024
Exercise 4:
37

 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

 Trace the following function calls and determine


returned result for each call?
int sum (int num)
{
if (num<=0)
return 0;
return sum( num-1) +num;
}
 Case: sum(5);
3/2/2024
39

Questions?
3/2/2024
40

Thank You
3/2/2024

You might also like