L08!09!24.10.2018 - Solving Recuurence Relations
L08!09!24.10.2018 - Solving Recuurence Relations
Review of Recursion
Solving Techniques
Substitution Method
Recurrence Tree Method
Master Method
What are the Basic Steps of
Mathematical Induction
Step 1: Basis (Base Case) We first establish that the proposition P (n) is true for
the lowest possible value of the positive integer n (=0 or 1).
Step 2: (Inductive Step) We assume that P (k) is true and establish that P (k+1) is
also true
Recurrences and Running Time
An equation or inequality that describes a function in
terms of its value on smaller inputs.
T(n) = T(n-1) + n
6
Recurrent Algorithms: BINARY-SEARCH
for an ordered array A, finds if x is in the array A[lo…hi]
if x = A[mid]
return TRUE
if ( x < A[mid] )
BINARY-SEARCH (A, lo, mid-1, x)
if ( x > A[mid] )
BINARY-SEARCH (A, mid+1, hi, x) 7
Example
1 2 3 4 5 6 7 8
1 2 3 4 5 7 9 11 mid = 4, lo = 5, hi = 8
5 6 7 8
1 2 3 4 5 7 9 11 mid = 6, A[mid] = x
Found!
8
Another Example
1 2 3 4 5 7 9 11 mid = 4, lo = 5, hi = 8
low high
1 2 3 4 5 7 9 11 mid = 6, A[6] = 7, lo = 5, hi = 5
low high
1 2 3 4 5 7 9 11 mid = 5, A[5] = 5, lo = 6, hi = 5
NOT FOUND!
1 2 3 4 5 7 9 11
high low
9
Analysis of BINARY-SEARCH
Alg.: BINARY-SEARCH (A, lo, hi, x)
if (lo > hi) constant time: c1
return FALSE
mid (lo+hi)/2 constant time: c2
if ( x > A[mid] )
BINARY-SEARCH (A, mid+1, hi, x) same problem of size n/2
T(n) = c + T(n/2)
T(n) – running time for an array of size n
10
Methods of Solving Recurrence Relations
Substitution
Iteration Method
Accounting method
Draw the recursion tree
The Master Theorem*
Guess at an upper bound, prove it
n 1 2 3 4 5 6
tn 1 3 7 15 31 63
Example: 4.2-4.10
Methods of Solving Recurrence Relations
Substitution
Iteration Method
Draw the recursion tree
The Master Theorem
• T(n) = T( n-1 ) + c
• “The cost of searching n elements is the
cost of looking at 1 element, plus the cost
of searching n-1 elements”
Md. Sabir Hossain, CSE, CUET
Linear Seach (cont)
Caveat:
• You need to convince yourself (and others) that the single
step, examining an element, *is* done in constant time.
• Can I get to the ith element in constant time, either
directly, or from the (i-1)th element?
• Look at the code
T(n) = T(n-1) + 1c 1
T(n) = T(n-2) + 2c 2
T(n) = T(n-3) + 3c 3
T(n) = T(n-4) + 4c 4
Md. Sabir Hossain, CSE, CUET
Linear Search (cont.)
• An expression for the kth unwinding:
T(n) = T(n-k) + kc
• We have 2 variables, k and n, but we have a relation
• T(d) is constant (can be determined) for some constant d
(we know the algorithm)
• Choose any convenient # to stop.
T(n) = T(n/2) + c 1
T(n) = T(n/4) + 2c 2
T(n) = T(n/8) + 3c 3
T(n) = T(n/16) + 4c 4
Example: 4.23-4.28
Self Study
Example: 4.13-4.16
Next 2/3 Classes