Question: 18) Given the following code snippet for searching an array: int[] arr = {3, 8, 12, 14, 17}; int newVal = 15; int pos =
18) Given the following code snippet for searching an array:
int[] arr = {3, 8, 12, 14, 17};
int newVal = 15;
int pos = Arrays.binarySearch(arr, newVal);
What value will pos have when this code is executed?
a) 5
b) -5
c) 6
d) -6
19) Assume that bands is an ArrayList of String objects which contains a number of elements in ascending order. Select a statement to complete the code segment below, which invokes the Java library binarySearch method to search for the string "Beatles". If the list does not already contain the string, it should be inserted in an appropriate location so that the list remains sorted.
int index = Collections.binarySearch(bands, "Beatles");
if (index < 0)
{ __________________________
}
a) bands.add(-1 * index + 1, "Beatles");
b) bands.add(index + 1, "Beatles");
c) bands.add(-1 * index, "Beatles");
d) bands.add(-1 - index, "Beatles");
20) The partial binary search method below is designed to search an array of String objects sorted in ascending order. Select the expression that would be needed to complete the method.
public static int search(String[] a, int low, int high, String item)
{ if (low <= high)
{ int mid = (low + high) / 2;
int result = ____________________________;
if (result == 0)
{ return mid;
}
else if (result < 0)
{ return search(a, mid + 1, high, item);
}
else
{ return search(a, low, mid - 1, item);
}
}
return -1;
}
a) a[low].compareTo(item)
b) item.equals(a[mid])
c) item.compareTo(a[mid])
d) a[mid].compareTo(item)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
