Orders of Growth

Order Linear Polynomial Exponential Factorial
Example nn n2n^2, n3n^3 2n2^n, ene^n, 10n10^n n!n!, nnn^n
n=1000n = 1000 10310^3 10610^6, 10910^9

Exercise:
For each of the following pairs of functions, indicate which one has a higher order of growth.

  1. n(n+1)n(n+1) and 2000n22000n^2
    • \approx same -- within constant multiple
  2. 100n2100n^2 and 0.01n30.01n^3
    • cubic has higher order of growth than quadratic
  3. log2n\log_2 n and lnn\ln n
    • All logarithmic functions have \approx same growth within const multiple (can change log's base by the formula logan=logablogbn\log_a n = \log_a b \log_b n)
  4. log22nlog_2^2 n and log2n2log_2 n ^2
    • log22n=log2nlog2n\log_2^2 n = \log_2n \log_2n and log2n2=2log2n\log_2 n^2 = 2 \log_2 n
  5. 2n12^{n-1} and 2n2^n
    • 2n1=122n2^{n-1} = \frac{1}{2} 2^n so \approx same order of growth as 2n2^n
  6. (n1)!(n-1)! and n!n!
    • (n1)!(n-1)! has lower order of growth since n!=n(n1)!n! = n(n-1)!

Analysis of Non-Recursive Algorithms

Procedure

Example 1:

Max Element
Input: an array, A
Output: the largest element in A

maxVal <- A[0]
for i <- 1 ... A.length-1
  if A[i] > maxVal
    maxVal <- A[i]
return maxVal

What is the input size? (A.length)
What is the basic operation? (Comparison)
What do we expect its complexity class to be? (Linear)

C(n)=i=1n11C(n) = \sum_{i=1}^{n-1} 1
=(n1)1+1= (n - 1) - 1 + 1 (from previous formula)
=(n1)Θ(n)= (n - 1) \in \Theta(n)


Example 2:

Bubble Sort
Input: an array, A of sortable elements
Output: a permutation of A in non-decreasing order

for i <- 0 ... A.length - 2
  for j <- 0 ... A.length - 2 - i
    if A[j+1] < A[j]
      swap A[j] and A[j+1]
return A

What's the input size? n = A.length
Basic operation? Swap
What do we expect its complexity class to be? Polynomial

C(n)=i=0n2j=0n2i1C(n) = \sum_{i=0}^{n-2} \sum_{j=0}^{n-2-i} 1
=i=0n2n1i= \sum_{i=0}^{n-2} n-1-i (the inner cycles happen n - i - 1 times)
=i=1n1i= \sum_{i=1}^{n-1} i
=n(n1)2Θ(n2)= \frac{n(n-1)}{2} \in \Theta(n^2)


Example 3:

Matrix Summation

Input: a w×hw \times h matrix, M
Output: The sum of all elements in M

total <- 0
for i <- 0 ... w - 1
  for j <- - ... h - 1
    total <- total + M[i][j]
return total

Input size? whw \cdot h
Basic operation? Addition
Expected complexity class? Linear

C(n)=i=0w1j=0h11C(n) = \sum_{i=0}^{w-1} \sum_{j=0}^{h-1} 1
=i=0w1h= \sum_{i=0}^{w-1} h
=hi=0w11= h \sum_{i=0}^{w-1} 1
=hw= h \cdot w =nΘ(n)= n \in \Theta(n)


Example 4:
Square Matrix Multiplication

Analysis


Example 5:

Uniqueness