Recursive Algorithm Analysis

limnf(n)g(n)=limnf(n)g(n)\lim_{n \to \infty} \frac{f(n)}{g(n)} = \lim_{n \to \infty} \frac{f'(n)}{g'(n)}


A recurrence relation is an equation that recursively defines a sequence of values given some initial terms.

Reviewish Examples:


Example: Find n!n!
NonRecursiveFindFactorial(n):

result = 1
for i <- 1 ... n
result = result * i
return result

Recurrence: f(n) = n * f(n - 1)

RecursiveRecursiveFindFactorial(n):
if n = 0
return 1
else
return n * RecursiveFindFactorial(n - 1)

Analysis of Recursive Algorithms (3 methods):

  1. Iteration Method

Example: n!n!
T(n)=T(n1)+1T(n) = T(n-1) + 1

T(n)=T(n1)+1T(n) = T(n - 1) + 1
=(T(n2)+1)+1= (T(n - 2) + 1) + 1
=T(n2)+2= T(n - 2) + 2
...
=T(ni)+i= T(n - i) + i
...
=T(0)+n=O(n)= T(0) + n = \mathcal{O} (n)

  1. Substitution Method
    Example:
    Let T(1)=4T(1) = 4
    T(n)=2T(n2)+4nT(n) = 2T(\frac{n}{2}) + 4n
Build solution by substituting scratch work Scratch pad
T(n)=2T(n2)+4nT(n) = 2T(\frac{n}{2}) + 4n T(n2=2T(n22)+4(n2)T(\frac{n}{2} = 2T(\frac{n}{2^2}) + 4(\frac{n}{2})
=2[2T(n22)+4n2]+4n= 2[ 2T(\frac{n}{2^2}) + 4\frac{n}{2}] + 4n
=22T(n22)+4n+4n= 2^2 T(\frac{n}{2^2}) + 4n + 4n
T(n22)=2T(n23+4(n22))T(\frac{n}{2^2}) = 2T(\frac{n}{2^3} + 4(\frac{n}{2^2}))
=22[2T(n23)+4n22]+4n+4n= 2^2 [2T(\frac{n}{2^3}) + 4 \frac{n}{2^2}] + 4n + 4n
=23T(nn3)+4n+4n+4n= 2^3 T(\frac{n}{n^3}) + 4n + 4n + 4n
Pattern??
T(n23)=2T(n24)+4(n23)T(\frac{n}{2^3}) = 2T(\frac{n}{2^4})+ 4(\frac{n}{2^3})
=23[2T(n24)+4(n23)]+4n+4n+4n= 2^3[2T(\frac{n}{2^4})+ 4(\frac{n}{2^3})] + 4n + 4n + 4n
=24T(n24)+4n+4n+4n+4n= 2^4 T(\frac{n}{2^4}) + 4n + 4n + 4n + 4n
=2iT(n2i)+i(4n)= 2^i T(\frac{n}{2^i}) + i(4n) We need to get to the base case: n2i=1\frac{n}{2^i} = 1 i.e. n=2in = 2^i log2n=i\to \log_2 n = i
Substitute into equation above:
2log2nT(1)+(log2n)(4n)2^{\log_2 n} T(1) + (\log_2 n) (4n)
=n(4)+4nlog2n=n(4) + 4n \log_2 n
=4n+4nlog2nO(nlog2n)=4n + 4n \log_2 n \in \mathcal{O}(n\log_2 n)
T(1)=4T(1) = 4 and 2log2n=nlog22=n1=n2^{\log_2 n} = n ^{\log_2 2} = n^1 = n
  1. Master Theorem

Useful Recurrence Types:
Linear: One (constant) operation reduces problem size by one.

Quadratic: A pass through input reduces problem size by one.

Logarithmic: One (constant) operation reduces problem size by half.

n log n: A pass through input reduces problem size by half.