List the numbers in each of the following ranges:
2..6
-1..3
Give the number of elements in each of the following ranges:
2..3
0..4
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?
A[0..A.length]
A[0..A.length-1]
A[0..A.length+1]
A[1..A.length-1]
left part
of the array diagram below:For each of the following three problems, write an expression for the subarray corresponding to the given shaded segment of in the following array diagram:
Light gray sement
Dark gray segment
Black segment
Consider the following Java method:
/** [[spec]]
: [[precondition]] */
Preconditionpublic static int sumRange(int[] A, int start, int end) {
int sum = 0;
// invariant: [[invariant]]
for (int i = start; i < end; i++) {
+= A[i];
sum }
return sum;
}
[[brackets]]
. Match each line with the placeholder it should replace.
Return the sum of the elements A[start..end]
sum contains the sum of A[start..i]
0 <= start <= end <= A.length
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]) {
= mid;
end } else {
= mid + 1;
start }
}
return -1;
}
4
in the following array?[1, 4, 5, 5, 5, 8, 10]
11
in the same array?