user1459010
user1459010

Reputation: 155

Binarysearch unsorted array

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

Upvotes: 1

Views: 7470

Answers (2)

Wormbo
Wormbo

Reputation: 4992

You are probably supposed to stick to the documentation, not to your knowledge of how binary search works in general. The API docs are pretty clear on using Array.binarySearch on unsorted arrays: "If it is not sorted, the results are undefined."

In other words, if the array is not sorted, the result is not required to follow any rules. From the implementation of binary search you may know that the result cannot exceed the array length. However, that's implementation detail. You cannot rely on that.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This is a trick question. The results of binary search on an unsorted array are undefined, as per documentation:

The array must be sorted (as by the sort method, above) prior to making this call. If it is not sorted, the results are undefined.

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 in 1 on the list of answers, so B and E is the choice the examiners expect you to make.

Upvotes: 9

Related Questions