Exercises - Lecture 1

1A

List the numbers in each of the following ranges:

  1. 2..6
  2. -1..3

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

  1. 2..3
  2. 0..4

  3. Recall that A.length gives the length of an array A, and Java array indices start at zero. Which of these denotes the subarray of A containing all of A’s elements?
  1. Write an expression that denotes the subarray containing all elements in the segment labeled left part of the array diagram below:

image-20200904101824778

For each of the following three problems, write an expression for the subarray corresponding to the given colored segment of in the following array diagram:

image-20200721222819355

  1. Red sement

  2. Green segment

  3. Blue segment

1B

Consider the following Java method:

  /** [[spec]] 
  Precondition: [[precondition]] */
  public static int sumRange(int[] A, int start, int end) {
    int sum = 0;
    // invariant: [[invariant]]
    for (int i = start; i < end; i++) {
      sum += A[i];
    }
    return sum;
  }
  1. The following three lines represent the spec, precondition, and invariant (but not necessarily in that order) for the above algorithm, to be substituted in for the placeholders in [[brackets]]. Match each line with the placeholder it should replace.
  2. Draw an array diagram illustrating the loop invariant.

1C

Here’s the code for binary search:

public static int binarySearch(int[] A, int x) {
    int start = 0;
    int end = A.length;
    // invariant: A[start] <= x <= A[end-1]
    while (start < end) {
      int mid = (start + end) / 2;
      if (x == A[mid]) {
        return mid;
      } else if (x < A[mid]) {
        end = mid;
      } else {
        start = mid + 1;
      }
    }
    return -1;
  }
  1. How many times does the loop execute when searching for the value 4 in the following array?
[1, 4, 5, 5, 5, 8, 10]
  1. How many times does the loop execute when searching for 11 in the same array?