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

ch02 Recursion

data structure recursion

Uploaded by

thomaselbitar
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)
8 views

ch02 Recursion

data structure recursion

Uploaded by

thomaselbitar
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/ 23

Chapter 2: Recursion

3
Plan
• Introduction
• Example: factorial Function
• Analyse of the recursion method
• Classical Problems
• Exe rcises

4
Introdu ction
• An algorithm uses one of two methods Iterative method, also called
iterative function based on loops and terminate its execution when
exiting the loop.
• Recursive method, also called recursive function This is when a
function calls itself - One or more times to accomplish a given task.
• Motivation: Recursive functions simplify the implementation of
algorithms They provide an elegant and comprehensive
representation Iterative functions are more efficient in terms of
performance A recursive function can always be implemented in
iterative form. 5
Example: Factorial Function
• Write an iterative function and a recursive function to calculate the
factorial of a number.

O! =1 Genera l form: n! = 1si n = 0


1! =1 n! = 1* 2 * ... * (n-1) * n si n > 0
2 ! =1 x 2
3 ! =1 x 2 x3

• General Form:
4! =4 x 3 x 2 x 1 n ! =1 si n =0
= 4 x (3 x 2 x 1)
n ! =n * (n-1) ! if n > O
=4 x 3 !
n I is defined in terms b y i t s e l f
Given f( n)=n I and f( n - l )=(n-1) I Alo rs f( n)=n*f(n-1)

6
Example: factorial function
#include <iostream>
Using namespace std;
double factorialiter (int n ) { //iterative function
double facto=l;
for (int i=l;i<=n;i++)
facto=i*facto;
return facto;
} Output
double factorial (int n ){ //recursive function
if (n <= 1) // cas de base
O! =1
1! 1
return 1;
return n*factorial (n-1) ; I I cas recursif
2! =2
3! 6
} 4! 24
int main (){ 5 ! = 120
int n;
6 ! = 720
for (int n=O ; n<=lO ; n++) 7! 5040
cout<<n<< " ! "<< factorial (n )<<endl;
8 ! = 40320
return 0 ;
9! 362880
} 10 ! = 3628800
Example: factorial function
Representation of recursive calls
Recursive calls
1 2 3 4
factoria l (4) factoria l(3) factoria l(2) factoria l(l )
n=4
4*factorial(3); n = 3;
)
3*factorial (2); n = 2·I
)
2*factorial (1); n = 1·I

-
....

1 return
-
. J

. J
2 return 2*1; 1;
'
. J
6 return 3*2;
'

- 24 return 4*6;

8
Example: factorial function
Representation of recursive
calls
4! 4! final value = 24

'' Returns 4!=4*6=24


' I

4 * 3! 4 * 3!
J'

I I
Returns 3 !=3* 2=6

3 * 2! 3 * 2!
'\
Returns 2!=2*1=2
' I

2 * 1! 2 * 1!
II

1 1

I Recursive calls Returned values at each recursive


call.
9
Example: Analysis factorial
function
• The recursive factorial function is based on: A basic case which is a

condition of termination, i.e. a condition that terminates recursive

calls e.g.

• for n<=l, the answer is known and is equal to 1 A general case

which is a general expression to calculate the factorial function in


I\.

terms of itself .

• e.g.,f{ n)=n*f{ n-1) which is n!=n*{ n-1)!


1
0
Analysis of the recursive
method
• To construct a recursive solution, we must understand the

problem and find the parameters of the recursive function.

• Find the base case(s) for which the solution(s) is known which

is a termination condition of the recursion.

• This prevents infinite recursion find the general case where

the solution can be expressed in terms of (or in part) of itself

which is a general expression.


1
1
CLASSIC PROBLEMS

12
Power Fonction

• Write an iterative function and a recursive


function that computes xn for n>O Iterative
scoring xn=x*x* ...x*x ; n multiplication by x
Recursive notation

• Basic case: x0=1

• General case: x"=x*x"-1

13
Iterative and recursive power
function
double poweriter (int x, int n) { double
pow=l;
for (int i=l;i<=n;i++) pow=x*pow;
return pow;
}
//x"n=x*x"(n-1)
double power (int x, int n){ if (n == 0)
return 1;
return x*power (x,n-1);
}

14
Power function
Representation of recursive calls
Appels recursifs
1 2 3 4 5

power(3,4) power(3,3) power(3,2) power(3,1) Power(3,0)


x=3· n=4 ·
J J
x=3· n=3·J x=3·
J
n=2·J x=3· n=1 ·
J J
X=3· n=0
J
......
J

3*power (3,3); 3*power(0)


3*power (3,2);
)
3*power (3,1); return 3.; Return 1
'

return 3*3 = 9

return
return 3*9
J
= 27
'
3*27 = 81·
J

15
Power function Recursive
Call representation
34 34 final value = 81
', J\

3* 33 3* 33
'I

'\

3* 32 3* 32 Return 33=3*32=27
'I
I\

3* 31 3* 31 Return 32=3*3=9
'
\

J'

3*3° 3* 3° Return 31=3*3°=3

', Return 1
3 1

IRecursive calls Returned values at each recursive call.


Function power
second method, more efficient
• if n is even: xn=(x n/2 ) 2 ; e.g.: 34 =(32 ) 2
• If n is odd: xn=(x(n-1)/2 ) 2 *x; e.g.: 35 =(32 ) 2 * 3
• Then the number of recursive calls will be almost reduced by
half
double power (int x, int n){
double res;
if (n == 0)
return 1; if (n%2==0){
res=power (x,n/2);
return res*res;
}
else {
res=power (x,n/2); return
x*res*res;
}
}

1
7
Binary search function

• It is also called dichotomous search. Because it


divides the elements of the array into two
different parts and repeats the division until
finding the index of the element In the middle part
of the table.
• The array must be arranged in ascending or
descending order.
1
8
Binary search function
//low means small indices
int BinSearch (int tab [], int low, int high, int
x){ int mid;
if (low>high){ return -1;
}
mid= (low+high)/2; if (x==tab [mid])
return mid;
if (x<tab [mid])
return BinSearch (tab,low, mid-1,x); else
return BinSearch (tab,mid+l,high,x);
}
General case: divide the table into two parts
each recursive call Basic case: Stopping when found in
the middle of an array.

19
Towers of Hanoi

A B c

• Three rods: A, B and C, n discs of different diameters are initially


placed as shown in the figure.
• The problem consists in moving the n discs on another rod
respecting the following conditions
• Move a single disk at once Never put on a disc a larger diameter
disc .
• Use an Intermediate Post.
20
Towers of Hanoi
• Parameters: n and A (origin rod), B (destination rod)
and C (intermediate rod)
• Basic case:
• If n=0, do nothing
• If n=1, move a disk from A to B
• General case: move n-1 disks from A to C
• move 1 disc from A to B
• move n-1 disks from C to B
• The algorithm is implemented elegantly with a
recursive function 21
Towers of Hanoi
void hanoi (int n, char source, char dest, char
interm){ if (n==l)
cout<<"Move the disk 1 from "<< source
<<" to " <<dest <<endl;
else {
Hanoi (n-1, source,interm,dest) •,

cout<<"Move the disk "<< n << " from


"
<<source<<" to "<<dest<<endl;
Hanoi (n-1,interm,dest,source);
}
}
Example, move 3 discs from 'A' to 'B' Calling Hanoi(3,'A','B','C')
generates the following output

Move t
disk 1 from A to B
h
e
Move t
disk 2 from A to C
h 22
EXERCISES

2
3
Exercise1 : Write an iterative function and a
Recursive function that calculates
Sn=tab[0]+tab[l]+...+tab[n- 1] where n is the
number of elements.
Exercise 2: Write a function that displays the
binary equivalent of a decimal number
Exercise 3: Write a recursive function that
displays an array of n characters

2
4
Exercise 4: Write a recursive function that prints upside
down an array of n characters.
Exercise 5: Write a recursive function that determines the
maximum of the elements in an array b of n integers.
Exercise 6: Write a recursive function that calculates the nth
element of the Fibonacci series Fib(n)=n if n ≤ 1
Fib(n)=fib(n-1)+fib(n-2)

2
5

You might also like