Kailash Kailash - 1 year ago 229
Java Question

Java Arrays binarySearch() insertion point

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


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)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download