Lecture 8 (DS) - Recursion
Lecture 8 (DS) - Recursion
Lecture # 8
Ehtisham Rasheed
5
Analysis of Recursion
• Time Complexity
• In case of recursion we try to figure out the number of times a recursive
call is being made. 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
• Calculates what amount of extra space is required for a module to
execute. In case of iterations, the compiler hardly requires any extra space.
In case of recursion, 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.
6
Factorial Function
• The product of the positive integers from 1 to n, inclusive, is
called “n factorial” and it usually denoted by n!
• Definition:
a) if n = 0, then n! = 1
b) if n > 0, then n! = n . ( n – 1 )! 7
Factorial Function (Continued…)
• Write a recursive function to calculate factorial of a given number
Long fact ( int num ) {
long f;
if ( num == 0 )
f = 1;
else
f = num * fact ( num – 1 )
return f;
} 8
Fibonacci Sequence
• The Fibonacci sequence (denoted by F0, F1, F2, …) is as follows:
• 0, 1, 1, 2, 3, 5,8, 13, 21, 34, 55, …
• That is, F0 = 0 and F1 = 1 and each succeeding term is the sum of
the two preceding terms. For example the next two terms of the
sequence are
• 34 + 55 = 89 and 55 + 89 = 144
• Definition:
a) if n = 0 or n = 1, then Fn = n
9
}
Recursion Example
• Let a and b denote positive integers. Suppose a function Q is
defined recursively as follows: