Recursion
Recursion
Lecture#13
Recursion
Recursion
• First of all, instead of giving the definition of Recursion, we give you an
example.
• You already know the Set of Odd numbers. Here we give the new definition of
the same set that is the set of Odd numbers
• Definition for odd positive integers may be given as:
• BASE:
• 1 is an odd positive integer
• RECURSION:
• If k is an odd positive integer, then k + 2 is an odd positive integer.
• Now, 1 is an odd positive integer by the definition base.
• With k = 1, 1 + 2 = 3, so 3 is an odd positive integer.
• With k = 3, 3 + 2 = 5, so 5 is an odd positive integer
• and so, 7, 9, 11, … are odd positive integers.
RECURSION:
log b x logy( x)
y b
x log(y ) y log(x )
log b (b) 1
log b (1) 0
8
Solving the Recurrence (By Iteration
Method)
• If n is assumed to be a power of 2 (2k = n) this will simplify
the recurrence to
1 if n 1
T (n)
2T (n / 2) n otherwise
9
Solving the Recurrence..
T (n) 2T (n / 2) n
2(2T (n / 4) n / 2) n
4T (n / 4) n n
4(2T (n / 8) n / 4) n n
8T (n / 8) n n n
8(2T (n / 16) n / 8) n n n
16T (n / 16) n n n n
10
The Iteration Method
(cont’d)
• If n is power of 2 then let n = 2k or k=log n.
k k
T (n) 2 T (n /( 2 )) (n n n ... n)
k times
k k
2 T (n /( 2 )) kn
(log n ) (log n )
2 T (n /( 2 )) (log n)n
(log n )
2 T (n / n) (log n)n
nT (1) n log n n n log n
11
Example-2: Solving Recurrence
f(n) = f(n -1 ) + n
= f(n- 2 ) + n - 1 + n
= f(n-3 ) + n - 2 + n - 1 + n
= f(n- 4 ) + n - 3 + n - 2 + n - 1 + n
…
= f( 1 ) + 2 + 3 + 4 + … + n - 1 + n
n(n 1) 2
(n )
2 12