Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is -(insertion_point - 1) returned by Collections.binarySearch when an element not present and not -insertion_point? [duplicate]

Tags:

java

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?

like image 524
rainkinz Avatar asked Nov 28 '22 21:11

rainkinz


1 Answers

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.

like image 158
James Montagne Avatar answered Dec 15 '22 04:12

James Montagne