CS352: Algorithms and Data Structures
 
 
 
Analysis of Fibonacci Series
 
unsigned int fib(unsigned int n)  
{  
(1)         if (n <= 1)  
(2)             return 1  
            else  
(3)             return ( fib(n-1) + fib(n-2) );  
} 

Let T(n) be running time for fib(n)

T(0) = T(1) = 1 since line(1) takes constant time.
when n>2 work consists of line 1 + line 3 (2 units time)
function calls: T(n-1) units for first call; T(n-2) units for second call

Running time of fib(n) is T(n) = T(n-1) + T(n-2) + 2
 
  • since it can be shown that fib(n) > (3/2n), it proves that fib(n) runs in exponential time
  • Example 2: Analyze the code fragment
     

     
    (1)     sum = 0;  
    (2)     for (j=1; j<=n; j++)  
    (3)         for (i=1; i<=j; i++)  
    (4)             sum++;  
    (5)     for (k=1; k<=n; k++)  
    (6)         A[k] = k-1;
     
    (1) assignment statement takes constant time: c1
    (5) for loop like ex.1 takes c2n = Q(n) time
    line (4) takes constant time: c3
    inner loop (3) executes j times --> cost c3j
    outer loop (2) executes n times, but cost of each inner loop is different with each j --> c3 * summation of j from 1 to n cost  = c1 + c2n + c3 * (n(n+1) / 2)
            = O(c1+c2n+c3 n2) = Q(n2)
                    Example 4. A for-loop that does not run in Q (n2) time
     
     sum=0;  
        for (k=1; k<=n; k*=2)  
            for (j=1; j<=n; j++)  
                sum++
     
    MAXIMUM SUBSEQUENCE SUM PROBLEM
                    Given (possibly negative) integers a1,a2,...,an, find the maximum value of  S ak. Ex. for input -2, 11, -4, 13, -5, -2, answer is 20 (a2 through a4)

    ALGORITHM : 1

        Line 1 is O(1); Loop line 2 is size n; Loop line 3 could be small or could be size n as well (worst case); Loop line 5 is size n;
        Lines 7 to 10 take O(n2)
        Total Running time is O(n3). More precisely, Q(n3)

    ALGORITHM : 2

        Third for-loop removed.
        Running time is O(n2)

    ALGORITHM : 3
     

      T(n) = time to solve problem of size n
    if n=1, T(n) = constant time = 1
    two loops run in O(n) time
    assignments run in constant time
    recursive calls: each solve 2 subsequence problems of size n/2 (if n is even)

    T(n/2) for each call => 2T(n/2) time

    Analysis vs Empirical Results
    Practical Complexities
              Function growth for various values of n…
     
    log n
    n
    n log n
    n2 
    n3
    2n
    0 1 0 1 1 2
    1 2 2 4 8 4
    2 4 8 16 64 16
    3 8 24 64 512 256
    4 16 64 256 4096 65,536
    5 32 160 1024 32,768 4,294,967,296