Chapter 2 - Recursion - p1
Chapter 2 - Recursion - p1
Chapter 2 – Recursion
Motivation
▪ recursive functions simplify the implementation of algorithms
- they give an elegant and comprehensive representation
▪ iterative functions are more efficient in terms of performance
A recursive function can always be implemented in an iterative form
2
Analysis of the recursive method
3
Example: factorial function
5
Example: factorial function : Iterative and Recursive
int factorialIter (int n) { //iterative function
int facto=1;
for(int i=1;i<=n;i++)
facto=i*facto;
return facto;
}
Recursive call
1 2 3 4
factorial (4) factorial(3) factorial(2) factorial(1)
n=4
4*factorial(3); n = 3;
3*factorial (2); n = 2;
2*factorial (1); n = 1;
1 return 1;
2 return 2*1;
6 return 3*2;
24 return 4*6;
7
Power function
8
x^n = ?
x^0 = 1
x^1 = x = x * 1 = x * x^0
x^2 = x * x = x * x^1
x^3 = x * x * x = x * x^2
x^4 = x * x * x * x = x * x^3
…
x^n = x* x*x*x…*x = x * x^(n-1)
x^n = 1 if n = 0
= x * x^(n-1) if n !=0
9
Power function: Iterative and recursive
10
Power function: Recursive calls representation
Recursive calls
1 2 3 4
power(3,4) power(3,3) power(3,2) power(3,1)
x=3; n=4;
3*power (3,3); x=3; n=3;
3*power (3,2); x=3; n=2;
3* power (3,1); x=3; n=1;
3 return 3;
9 return 3*3;
27 return 3*9;
81 return 3*27;
11
Power function: 2nd method, more efficient
power(2,5)
x=2, n=5, odd
res = power(2,2) → power(2,2)
return 2*res*res x=2, n=2, even
res = power(2,1) → power(2,1)
return res*res x=2, n=1
return 2
13
Sum function in an array
14
1st method
int sum(int *A, int n, int i) Sum ( 1 2 3 4 5 6 )
{
if(i == n) = 1 + Sum( 2 3 4 5 6 )
return 0;
return A[i] + sum (A, n, i+1); = 1 + 2 + Sum( 3 4 5 6 )
}
= 1 + 2 + 3 + Sum( 4 5 6 )
Main call: S = sum (tab, 6, 0);
= 1 + 2 + 3 + 4 + Sum( 5 6 )
= 1 + 2 + 3 + 4 + 5 + Sum( 6 )
Sum([1,2,3,4,5,6]) return 1 + S([2,3,4,5,6]), return 1 + 20 → return 21
Sum([2,3, 4, 5, 6]) return 2 + S ([3, 4, 5, 6]), return 18 + 2 → return 20
= 1 + 2 + 3 + 4 + 5 + 6 + Sum( )
Sum([3, 4, 5, 6]) return 3 + S([4, 5, 6]), return 3 + 15 → return 18
Sum([4, 5, 6]) return 4 + S([5, 6 ]), return 4 + 11 → return 15
= 1 + 2 + 3 + 4 + 5 + 6 + 0 = 21
Sum([5, 6]) return 5 + S([6]), return 5 + 6 → return 11
Sum([6]) return 6 + S([]), return 6 + 0 → return 6
Sum([]) return 0
15
2nd method
int Sum(int *A, int n) Sum ( 1 2 3 4 5 6 )
{
if(n==0) = 6 + Sum( 1 2 3 4 5 )
return 0;
return A[n-1]+Sum(A,n-1); = 6 + 5 + Sum( 1 2 3 4 )
}
= 6 + 5 + 4 + Sum( 1 2 3 )
= 6 + 5 + 4 + 3 + Sum( 1 2 )
16