Hopefully someone knows the answer to this Java-Certification question:
public static void main(String[] args) {
String[] sa = {"d", "c", "a", "b" };
int x = Arrays.binarySearch(sa, "b");
Arrays.sort(sa);
int y = Arrays.binarySearch(sa, "b");
System.out.println(x + " " + y);
}
Which two results are possible? (Choose two.)
A) 7 0
B) 7 1
C) 7 3
D) -1 0
E) -1 1
F) -1 3
The only true answer is E) -1 1, because if you play through the binary-search-algorithm this is the only possible output. But they want me to choose two…
So the second one have to be B) 7 1 then, because the second binarySearch in the sorted array will always return 1.
So my Question is, why is B) 7 1 a possible result?
More specific: How is it possible, that the first binarySearch in the unsorted array returns 7?
Thanks in advance
This is a trick question. The results of binary search on an unsorted array are undefined, as per documentation:
This means in particular that any number, including seven, is fair game.
The results on a sorted one are well-defined: you’ll get a
1. As if by magic, there are only two pairs that end in1on the list of answers, soBandEis the choice the examiners expect you to make.