CMPS 144   Computer Science 2
Sample Problems: Analysis of Algorithms

1. In the following code segments, S, S1, S2, and S3 represent sequences of commands that execute in constant time. For each code segment, give an estimate of the number of times each of its innermost loops iterates, as a function of the value of variable n. Then express the code segment's asymptotic running time using big-Oh notation.

         code segment                      # iterations       running time
    ------------------------               ------------      --------------

(a) for (int i=0; i != n/2; i = i+1) {
      S1
      for (int j=0; j != n; j = j+1)           n2/2            O(n2)
        { S2; }
      S3
    }


(b) for (int i=0; i != n; i = i+1) {
      for (int j=0; j != i; j = j+1) {       (n3 + n2)/2       O(n3)
        for (int k=0; k != n; k = k+1)
          { S; }
      }
    }
        

(c) int i = 0;
    while ( i != 13 ) {
      for (int j=0; j != n; j = j + 1)            13n         O(n)
        { S; }
      i = i+1;
    }

(d) int i = n 
    while (i > 0) {
      S;                                         n/3          O(n)
      i = i - 3;
    }

(e) int i = n 
    while ( i > 0 ) {
      S;                                        log3n         O(log n)
      i = i / 3;
    }