0% found this document useful (0 votes)
150 views

Chapter 6 - Recursion

computer organization and architecture power point for unifying concepts visualized at the specified level of accuracy for most students that are in a close relationship with the behavior and operating of computer systems involving core concepts under the likelihood of theorists.

Uploaded by

Desyilal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
150 views

Chapter 6 - Recursion

computer organization and architecture power point for unifying concepts visualized at the specified level of accuracy for most students that are in a close relationship with the behavior and operating of computer systems involving core concepts under the likelihood of theorists.

Uploaded by

Desyilal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Chapter 6

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

▪ Sometimes, the best way to solve a problem is by solving a


smaller version of the exact same problem first.
▪ In some 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.
▪ Recursion is a technique that solves a problem by solving a
smaller problem of the same type.

5/25/2021 3
Problems defined recursively

▪ There are many problems whose solution can be defined recursively


Example: n factorial

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 Iterative implementation


implementation
int Factorial(int n)
int Factorial(int n) {
int fact = 1;
{
if (n==0) // base case for(int count = 2; count <= n; count++)
return 1; fact = fact * count;
else
return n * Factorial(n-1); return fact;
}
}
How factorial is computed using recursion
Function Call

▪ So far, we have seen methods that call other functions.


– For example, the main() function calls the square() function.
main()
factorial()

▪ Recursive Function:
– A recursive function is a function that calls itself.

compute()

5/25/2021 7
Properties

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

5/25/2021 8
Cont…

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.

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])

▪ What is the base case(s)?


(1) If first > last, return false
(2) If item==info[midPoint], return true

▪ What is the general case?


if item < info[midPoint] search the first half
if item > info[midPoint], search the second half
Recursive binary search (cont’d)
bool BinarySearch(int info[], int & item, int first, int last)
{
int midPoint;
if(first > last) // base case 1
return false;
else {
midPoint = (first + last)/2;
if(item < info[midPoint])
return BinarySearch(info, item, first, midPoint-1);
else if (item == info[midPoint]) { // base case 2
item = info[midPoint];
return true;
}
else
return BinarySearch(info, item, midPoint+1, last);
}
}
Exercise:

▪ Write a recursive functions for the following problems?


– Determine the base case and general case?
1. Write a function that takes n as input and find the sum of all
consecutive positive integers from n to 1.
2. Write a recursive function that computes a power of a number
i.e xn

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

double power(double x, int n) {


if (n <= 0) // base case
return 1;
else
return x * power(x, n-1); //Recursive case
}

18
Implementation : Recursive function

▪ 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.
– This transfer 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.
5/25/2021 19
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.)

▪ An activation record is stored into a stack (run-time stack)


1) The computer has to stop executing function b and starts
executing function a
2) Since it needs to come back to function b later, it needs to store
everything about function b that is going to need (x, y, z, and the
place to start executing upon return)
3) Then, x from a is bounded to w from b
4) Control is transferred to function a
What happens when a
function is called? (cont.)

▪ After function a is executed, the activation record is popped


out of the run-time stack
▪ All the old values of the parameters and variables in function b
are restored and the return value of function a replaces a(x) in
the assignment statement
What happens when a
recursive function is 2*f(2)
called?

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.

▪ 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;

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

▪ 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
5/25/2021 29
Deciding whether to use a recursive
solution

1. When the depth of recursive calls is relatively


"shallow"
2. The recursive version does about the same
amount of work as the non-recursive version
3. The recursive version is shorter and simpler than
the non-recursive solution

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

You might also like