[1] Java Program : Suppose that we have an array called list initialized as foll
ID: 3772176 • Letter: #
Question
[1] Java Program : Suppose that we have an array called list initialized as follows: (4 pts)
int[] list = {-2, 8, 13, 22, 25, 25, 38, 42, 51, 103};
This would construct the following array:
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| -2 | 8 | 13 | 22 | 25 | 25 | 38 | 42 | 51 | 103 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
The following explains two types of binarySearch method in the Arrays class.
public static int binarySearch(int[] a, int target) {
return binarySearch(a, target, 0, a.length - 1);
}
public static int binarySearch(int[] a, int target,
int min, int max) {
if (min > max) {
return -1; // target not found
} else {
int mid = (min + max) / 2;
if (a[mid] < target) { // too small; go right
return binarySearch(a, target, mid + 1, max);
} else if (a[mid] > target) { // too large; go left
return binarySearch(a, target, min, mid - 1);
} else {
return mid; // target found; a[mid] == target
}
}
}
Please write complete BinarySearch class program with the above methods and the method calls as follows and give the answer for the following questions.
System.out.println(binarySearch(list, 103, 0, 9));
System.out.println(binarySearch(list, 30, 2, 8));
[1.1] What values would min, max and mid take on for the following call in recursive fashion:
binarySearch(list, 103, 0, 9);
and what value would be returned?
[1.2] What values would min, max and mid take on for the following call in recursive fashion:
binarySearch(list, 30, 2, 8);
and what value would be returned?
Explanation / Answer
1.
System.out.println(binarySearch(list, 103, 0, 9));
min max mid
5 9 7
8 9 8
9 9 9
value return = 9
2.
System.out.println(binarySearch(list, 30, 2, 8));
min max mid
2 8 5
6 8 7
6 6 6
value return = -1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.