Lecture 1 - Problems

Give the number of elements in each of the following ranges:

  1. 0..x (assume x >= 0)
  2. a..b (assume a <= b)

Consider the following Java method:

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. Determine what the code does and write a concise method specification for the method.

  2. A good way to think about preconditions is as a way to avoid having to handle inputs that don’t make sense. If a method can be called with syntactically correct inputs but nonetheless result in an error, the method should either handle that case explicitly, or have a precondition that says such an input is not allowed. Determine whether the method needs any preconditions; if so, list them; if not, explain why not.

  3. Sometimes, a method’s postcondition is very similar to the description already given in the specification, and we don’t need to list it. In this case, let’s be overly explicit and write a postcondition for the method.

  4. Write a loop invariant for the for loop in the above code.

  5. Consider the following array diagrams describing a precondition and postcondition for the for loop in the above code. Note that these are pre- and postconditions for the loop, which are distinct from the method’s pre/postconditions you wrote in Problems 2 and 3.

    image-20200723212240176

    Draw an array diagram that represents the loop invariant. Keep in mind that the loop invariant should match the precondition before the loop starts (when i==0) and should match the postcondition when the loop ends (when x is found or i==A.length).

  6. Here’s the code for binary search:

    Write a specification for the above method, including any applicable preconditions and postconditions.

  7. Draw the array diagram of the loop invariant for binarySearch.

  8. Suppose you’re using linearSearch (the method from Problems 1-5) to search for value in an array. What’s the maximum number of iterations of the for loop your code could execute if the array has length:

  1. Suppose you’re using binarySearch to search for a value in an array. What’s the maximum number of iterations of the while loop your code could execute if the array has length:
  1. Based on the above, it seems like binarySearch is a better choice if your array is sorted, as determined by the number of loop iterations performed. Think about how you might generalize this kind of comparison to work with any pair of algorithms to compare them and decide which one will be “faster”. Note: There is no single correct answer to this question; we’ll be thinking more about this in the next lecture and going forward.