14: Running Time

Submit this homework using Gradescope. You can type up your answers, or write legibly and scan them. Do not attempt to submit a paper copy in class, as it will not be accepted.


State the approximate worst-case running time for each of the following. If you are unsure of one of the calls into the Java Platform APIs, think about how the method might be implemented, and/or read its documentation.

Appropriate answers are of the form “constant time” or “[X] in [Y]”, where [X] might be “linear,” “quadratic,” or the like, and [Y] is the name of the variable or quantity in question. For example, a traversal of an array is linear in the length of the array; if the array is named a, it is linear in a.length. (1 point each)

A.

void reverse(int[] a) {
  for (int front = 0; front < a.length / 2; front++) {
    int rear = a.length - 1 - front;
    int t = a[front];
    a[front] = a[rear];
    a[rear] = t;
  }
}

B.

int manhattanDistance(int x1, int y1, int x2, int y2) {
  return Math.abs(x2 - x1) + Math.abs(y2 - y1);
}

C.

int allPairsProductSum(int[] a) {
  int result = 0;
  for (int i: a) {
    for (int j: a) {
      result += i * j;
    }
  }
  return result;
}

D. ArrayList(Collection<? extends E> c) (that is, the copy constructor for ArrayList)

E. ArrayList.size

F. Arrays.binarySearch (Hint: maybe Google for “binary search