Analysis of an Algorithm

Document last modified: 

Assignment

  1. Write down for each statement the number of times the statement is executed in the worst case.
  2. Compute T(n), i.e., the running time of Find_Largest, and simplify (if possible) by combining terms.
  3. What data produces the worst case? The best case?
  4. Is the worst case actually any worst than the best case? Think Big-O.
  5. Write down the for loop's loop invariant.
Find_Largest (A)
//@ pre A != null;
//@ post (\forall int i; 1 <= i && i <= A.length; A[\result] >= A[i]);
//    post: result = index in A of the largest element in A 

 

Cost

Times Executed

1    location ← 1 c1  1
2    for i ← 2 to length[A] do c2  n
3       if A[location] < A[i] then c3  n - 1
4          location ← i c4  n - 1
5    return location c5  1
  1. Compute T(n), i.e., the running time of Find_Largest, and simplify (if possible) by combining terms.

    T(n) = c1 + c2n + c3(n - 1) + c4(n - 1) + c5 

           = c1 + n(c2+c3+c4) - (c3+c4) + c5 

           = n(c2+c3+c4) + c1 + c5 - (c3+c4)

           = an + b                 for some constants a and b.

     

  2. What data produces the worst case? Data that executes line 4 each iteration, when sorted in ascending order.
     

    The best case? Data that never executes line 4, when sorted in descending order.
     

  3. Is the worst case actually any worst than the best case? Think Big-O.

    No. O(n) = T(n) = an + b
     

  4. Write down the for loop's loop invariant.

    The loop invariant is:

        /*@ loop_invariant (\forall int j;

                                         1<=j && j < i && 1 <= location && location < i;

                                         A[j] <= A[location]);                                                     @*/