SCJP 5 (98%) - SCBCD 5 (98%)
Unsuccessful searches return an int index that represents the insertion point.
The insertion point is the place in the collection/array where the element
would be inserted to keep the collection/array properly sorted. Because posi-
We�ve talked a lot about sorting by natural order and using Comparators
to sort. The last rule you�ll need to burn in is that, whenever you want to sort an array
or a collection, the elements inside must all be mutually comparable. In other words, if you
have an Object[] and you put Cat and Dog objects into it, you won�t be able to sort
it. In general, objects of different types should be considered NOT mutually comparable,
unless specifically stated otherwise.
tive return values and 0 indicate successful searches, the binarySearch()
method uses negative numbers to indicate insertion points. Since 0 is a valid
result for a successful search, the first available insertion point is -1. Therefore,
the actual insertion point is represented as (-(insertion point) -1). For
instance, if the insertion point of a search is at element 2, the actual insertion
point returned will be -3.
SCJP 5 (98%) - SCBCD 5 (98%)
are wrong. -1 is returned, if the the element used in binarySearch is less than the smallest element in the array (that is, it has to be inserted at position 0 to keep the array sorted). Let a = {0,2,4,6,8}. Than Arrays.binarySearch(a,1) would return -2, because 1 has to be inserted at index position 1 to keep the array sorted. And so on.No insert Point --> -1
At 0 --> -2
At 1 --> -3
At 2 --> -4
At 3 --> -5
SCJP 5 (98%) - SCBCD 5 (98%)
SCJP 5 (98%) - SCBCD 5 (98%)
SCJP 5 (98%) - SCBCD 5 (98%)