Exercises - Lecture 2

2A

  1. Consider the following Java method:

    /** Swap A[i] with A[j] 
      * Precondition: 0 <= i, j < A.length */
    public static void swap(int[] A, int i, int j) {
      int tmp = A[i];
      A[i] = A[j];
      A[j] = tmp
    }

    Which of the following are constant-time operations?

    1. Retrieving the value of i from memory in the first line of the method body
    2. Storing the value of tmp at A[j]
    3. All of the line int tmp = A[i]
    4. Calling swap(X, 2, 7), where X is an int[]
  2. Recall our linear search method:

    /** Return the index of x in A, or -1 if it doesn't exist. */
    public static int linearSearch(int[] A, int x) {
      for (int i = 0; i < A.length; i++) {
        if (A[i] == x) {
          return i;
        }
      }
      return -1;
    }

    Which of the following are constant-time operations?

    1. return i;
    2. Executing the comparison A[i] == x
    3. Calling linearSearch(X, 17), where X is an int[]

2B

  1. Give the asymptotic runtime class (big-O runtime) for an algorithm with each of the following operation counts:
    1. \(4N + 6\)
    2. \(\frac{N^3}{4} - 7\)
    3. \(842\)

Here’s linearSearch again:

/** Return the index of x in A, or -1 if it doesn't exist. */
public static int linearSearch(int[] A, int x) {
  for (int i = 0; i < A.length; i++) {
    if (A[i] == x) {
      return i;
    }
  }
  return -1;
}
  1. Let \(N\) be the size of A[]. In terms of \(N\), give the number of primitive operations performed by a call tolinearSearch if x does not appear anywhere in A. As we did in the examples from the video, follow the convention that any number of constant-time operations performed by a single line of code count as one.
  2. Give asymptotic runtime class of linearSearch based on the above count.
  3. Could the runtime class you gave in #5 be different if you counted every single primitive operation rather than grouping them per-line? Why or why not?
  4. Now assume that the value x appears at A[0]. What is the operation count in this situation?
  5. If for some reason we knew that x will always appear at A[0], what would the big-O (asymptotic) runtime of the algorithm be?

2C

  1. What’s the best, worst, and average case asymptotic runtime class for the following algorithm? For average case, assume that any value of n is equally likely.

    /** Print some numbers. Pre: n >= 0 */
    public static void alg2(int n) {
      n *= 4;
      if (n % 5 == 0) {
        System.out.println("42");
        return;
      }
      while (n > 0) {
        System.out.println(n);
        n /= 2;
      }
    }