Been using the binarySearch method and wondering why is -(insertion_point - 1) returned by Collections.binarySearch when an element not present and not -insertion_point? I understand why it is negative, but why the -1?
Because you can't have negative 0.
Consider the situation if there was no -1
. If an element was found at index 0, it would return 0. If an element was not found, but it's insertion point was 0, it too would return zero. How could you distinguish between these two situations? With the addition of the -1
, now they return 0
and -1
respectively, letting you distinguish.
And it is -(insertion point) - 1
which is slightly different than what your question states.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With