Reputation: 39
In standard Java 11 library if element is not found, method should return:
...the index of the first element greater than the key...
on Java 11 this sample prints 17
int[] data = new int[] {2, 4, 5, 12, 17, 19};
System.out.println(data[-1 *Arrays.binarySearch(data, 6)]);
In this code sample, first element greater than 6 is 12, but it returns index of 17. Why?
Upvotes: 0
Views: 238
Reputation: 40048
binarySearch(int[] a, int key) : If the element is not present it returns the index of (-(insertion point)-1)
. So in the above case insertion point is 3
and the expression is evaluated to -4
(-(3)-1) --> (-3-1) --> -4
And the array with corresponding value at index 4 is 17
Array --> {2, 4, 5, 12, 17, 19}
indexes -->0 1 2 3 4 5
index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
Upvotes: 5