0

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?

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I have read this but actual returning value is not relevant to this
I don't understand where you are getting confused @tengreencolors, it is returning as mentioned in documentation
@tengreencolors The return value you're seeing is exactly described by this. 6 is not in the array. It's insertion point would be 3, so Arrays.binarySearch(data, 6)] returns -insertion_point - 1, which is -3 - 1 which is -4.
@Deadpool My bad, I did not read doc carefully and after your explanation with actual values I finally got it, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.