Chapter 6 - Recursion
Chapter 6 - Recursion
Recursion
CH-5 Contents
1. Recursion basic
2. How do we write a recursive function?
3. How recursion is implemented
4. Recursion vs Iteration
5. Exercises
5/26/2021 2
Recursion - Basics
5/25/2021 3
Problems defined recursively
1 if n = 0
n!= (recursive solution)
(n-1)!*n if n > 0
1 if n = 0
n!= (closed form solution)
1*2*3*…*(n-1)*n if n > 0
Coding the factorial function
▪ Recursive Function:
– A recursive function is a function that calls itself.
compute()
5/25/2021 7
Properties
5/25/2021 8
Cont…
5/25/2021 9
How do we write a recursive function?
▪ 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" 5/25/2021 10
Three-Question Verification Method
▪ 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?
5/25/2021 11
General Form of Recursive Functions
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
}
} 5/25/2021 12
Binary search
Non-recursive implementation
Bool BinarySearch(int info[], int& item, int len){
int midPoint;
int first = 0;
int last = len - 1;
bool found = false;
while( (first <= last) && found) {
midPoint = (first + last) / 2;
if (item < info[midPoint])
last = midPoint - 1;
else if(item > info[midPoint])
first = midPoint + 1;
else {
found = true;
item = info[midPoint];
}} return found;}
Recursive binary search (cont’d)
▪ What is the size factor?
The number of elements in (info[first] ... info[last])
5/25/2021 16
Recursive Definitions: Sum
i. Sum(0) = 0 =0
ii. Sum(1)=1 =1
iii. Sum(2)=2+1 =3
iv. Sum(3)= 3+2+1 =6
double sum(int n) {
if (n <= 1) // base case
return n;
else
return n + sum(n-1); //Recursive case
}
5/26/2021 17
Recursive Definitions: Power
▪ x0 = 1 base case
▪ xn = x * xn-1 recursive case
18
Implementation : Recursive function
▪ 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.
– local variables, formal parameters, return address and all information
passed to the caller function.
▪ For this purpose, an activation record (or stack frame) is created for
the caller function.
5/26/2021 20
Implementation : Recursive function
▪ What happens when a function gets called?
int a(int w)
{
return w+w;
}
int b(int x)
{
int z,y;
……………… // other statements
z = a(x) + y;
return z;
}
What happens when a function is
called? (cont.)
2*f(1)
int f(int x)
{ 2*f(0)
int y;
if(x==0)
return 1;
else { =f(0)
y = 2 * f(x-1);
return y+1;
}
}
=f(1)
Note:
Except the fact that the calling =f(2)
and called functions have
the same name, there is
really no difference =f(3)
between recursive and non-
recursive calls
How to Trace Recursive Calls?
▪ 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.
5/25/2021 25
Another Example
5/25/2021 26
Tracing factorial function
5/25/2021 27
Analysis of Recursion
▪ One may argue why to use recursion, as the same task can be done with
iteration.
– The first reason is, recursion makes a program more readable and
results in fewer lines of code.
▪ Time Complexity
▪ A call made to a function is Ο(1), hence the (n) number of times a
recursive call is made makes the recursive function Ο(n).
▪ Space Complexity
▪ 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.
5/26/2021 28
Recursion vs. iteration
5/25/2021 30
Exercise 1: Q1
▪ Trace the following function calls and determine returned result for
each call? Case: print(5);
5/25/2021 31
Exercise 1: Q2
▪ Trace the following function calls and determine returned result for
each call? Case: print(5);
5/25/2021 32
Exercise 2:
▪ 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);
5/25/2021 33
Exercise 3:
▪ 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);
5/25/2021 34
Exercise 4:
▪ 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);
5/25/2021 35
Exercise
▪ Trace the following function calls and determine returned result for
each call?
5/26/2021 36
Next Time!!
Ch7 Binary Tree
–
5/26/2021 37