ReviewIntroduction to SearchingExternal and Internal SearchingTypes of Searching
Linear or sequential searchBinary Search
Algorithms for Linear SearchAlgorithms for Binary Search
1
Recursion
2
Introduction to Recursion Recursive DefinitionRecursive AlgorithmsFinding a Recursive SolutionExample Recursive Function Recursive ProgrammingRules for Recursive FunctionExample Tower of HanoiOther examples
Introduction
Any function can call another functionA function can even call itselfWhen a function call itself, it is making a
recursive callRecursive Call
A function call in which the function being called is the same as the one making the call
Recursion is a powerful technique that can be used in place of iteration(looping)
RecursionRecursion is a programming technique in which
functions call themselves.
3
Recursive Definition
4
A definition in which something is defined in terms of smaller versions of itself.
To do recursion we should know the followingsBase Case:
The case for which the solution can be stated non-recursively
The case for which the answer is explicitly known.
General Case:The case for which the solution is
expressed in smaller version of itself. Also known as recursive case
Recursive Algorithm
5
DefinitionAn algorithm that calls itself
ApproachSolve small problem directlySimplify large problem into 1 or more smaller
sub problem(s) & solve recursivelyCalculate solution from solution(s) for sub
problem
Finding a Recursive Solution
6
a recursive solution to a problem must be written carefully
the idea is for each successive recursive call to bring you one step closer to a situation in which the problem can easily be solved
this easily solved situation is called the base case
each recursive algorithm must have at least one base case, as well as a general
(recursive) case
Example 1
7
We can write a function called power that calculates the result of raising an integer to a positive power. If X is an integer and N is a positive integer, the formula for is
We can also write this formula as
Also as
In fact we can write this formula as
timesN
N XXXXXXX
*....*****
timesN
N XXXXXXX_)1(
*....*****
timesN
N XXXXXXX_)2(
*.....*****
1* NN XXX
NX
8
Recursive Power Function
Now lets suppose that X=3 and N=4
Now we can simplify the above equation as
So the base case in this equation is
int Power ( int x , int n )
{
if ( n == 1 )
return x; //Base case
else
return x * Power (x, n-1);
// recursive call
}
43NX
34 3*33 23 3*33 12 3*33
331
9
Example 2 (Recursive Factorial Function)
Factorial Function:Given a positive integer n, n factorial is defined as
the product of all integers between 1 and n, including n.
So we can write factorial function mathematically as
elsenfn
nnf
)1(
0 if1)(
10
Example 2 (Recursive Factorial Function)
Factorial definitionn! = n × n-1 × n-2 × n-3 × … × 3 × 2 × 10! = 1
To calculate factorial of nBase case
If n = 0, return 1Recursive step
Calculate the factorial of n-1Return n × (the factorial of n-1)
11
Example 2 (Recursive Factorial Function)
int factorial(n){
if(n == 0) //Base Case
return 1;else return n * factorial(n-1);
//Recursive Case}
12
Evaluation of Factorial ExampleTo evaluate Factorial(3)evaluate 3 * Factorial(2)
To evaluate Factorial(2)evaluate 2 * Factorial(1)
To evaluate Factorial(1)evaluate 1 * Factorial(0)
Factorial(0) is 1Return 1
Evaluate 1 * 1Return 1
Evaluate 2 * 1Return 2
Evaluate 3 * 2Return 6
13
Recursive Programming
main
factorial(3)
factorial(2)
factorial(1)
factorial(3)
2*factorial(1)
3 * factorial(2)
return 1
return 6
1*factorial(0)
factorial(0)
return 1
return 2
14
Rules For Recursive Function
1. In recursion, it is essential for a function to call itself, otherwise recursion will not take place.
2. To stop the recursive function it is necessary to base the recursion on test condition and proper terminating statement such as exit() or return must be written using if() statement.
3. When a recursive function is executed, the recursive calls are not implemented instantly. All the recursive calls are pushed onto the stack until the terminating condition is not detected, the recursive calls stored in the stack are popped and executed.
4. During recursion, at each recursive call new memory is allocated to all the local variables of the recursive functions with the same name.
15
The Runtime Stack during Recursion
To understand how recursion works at run time, we need to understand what happens when a function is called.
Whenever a function is called, a block of memory is allocated to it in a run-time structure called the stack.
On this stack an activation record for the function call is placed
This block of memory will contain the function’s local variables, local copies of the function’s call-by-value
parameters,pointers to its call-by-reference parameters, anda return address, in other words where in the
program the function was called from. When the function finishes, the program will continue to execute from that point.
Cont…
16
the activation record for a particular function call is popped off the run-time stack when the final closing brace in the function code is reached, or when a return statement is reached in the function code
at this time the function’s return value, if non-void, is brought back to the calling block return address for use there
A Stack of Activation Record
17
S(1)
S(2)
S(3)
S(4)
Main()
18
Exercise1. The problem of computing the sum of all
the numbers between 1 and any positive integer N can be recursively defined as:
i = 1
N
i = 1
N-1
i = 1
N-2
= N + = N + (N-1) +
= etc.
19
Exercise
int sum(int n){if(n==1)
return n;else
return n + sum(n-1);}
Example: Tower of Hanoi
20
Recursive algorithm especially appropriate for solution by recursion
TaskMove disks from left peg to right peg When disk moved, must be placed on a pegOnly one disk (top disk on a peg) moved at a timeLarger disk may never be placed on a smaller disk
Cont….
21
Identify base case:If there is one disk move from A to C
Inductive solution for n > 1 disksMove topmost n – 1 disks from A to B, using
C for temporary storageMove final disk remaining on A to CMove the n – 1 disk from B to C using A for
temporary storage
Cont…
22
Note the graphical steps to the solution
The Recursive GCD Function
23
Greatest common divisor (gcd) is the largest factor that two integers have in common
Computed using Euclid's algorithm:gcd(x, y) = y if y divides x evenlygcd(x, y) = gcd(y, x % y)otherwisegcd(x, y) = y is the base case
Cont…
24
int gcd(int x, int y){if (x % y == 0)return y;elsereturn gcd(y, x % y);}
Solving Recursive defined problems
25
The natural definition of some problems leads to a recursive solution
Example: Fibonacci numbers:0, 1, 1, 2, 3, 5, 8, 13, 21, ...After the starting 0, 1, each number is the
sum of the two preceding numbersRecursive solution:fib(n) = fib(n –1) + fib(n –2);Base cases: n <= 0, n == 1
Cont…
26
int fib(int n){
if (n <= 0)return 0;else if (n == 1)return 1;elsereturn fib(n –1) + fib(n –2);
}
Summary
27
Introduction to RecursionRecursive DefinitionRecursive AlgorithmsFinding a Recursive SolutionExample Recursive Function Recursive ProgrammingRules for Recursive FunctionExample Tower of HanoiOther examples