11

As per Java doc for Arrays.binarySearch(int[] a, int key)

Returns:

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.

I need to understand why its returning (-(insertion point) - 1), why not just -(insertion point)?

2 Answers 2

33

Because if it returned -(insertion point), and the insertion point was 0, then you would not be able to distinguish between I found it, it's at index 0, and I haven't found it, you can insert at index 0.

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

Comments

9

Consider an array:

int intArr[] = {5,12,20,30,55};

now consider these two binary search statements:

System.out.println("The index of element 5 is : " + Arrays.binarySearch(intArr,5));

and

System.out.println("The index of element 4 is : " + Arrays.binarySearch(intArr,4));

Output

The index of element 5 is : 0
The index of element 4 is : -1

because of that -1, we can differentiate between the two outputs. If there was no -1 then both of these statements would have given the same output, i.e., 0.

Comments

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.