Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Insertion Point Question on binarySearch()

Ranch Hand
Posts: 92

Results are:

four one three two
one = 1
--- reverse ---
two three one four
one = -1
one = 2

Why "-1"?

Martin Sergeant
Greenhorn
Posts: 24
The reason for the -1 is because binary search was not called using the same comparator that was used to
sort the array. According to the Sierra and Bates book, this will give an unpredictable result, in this case -1.
I am not sure why exactly -1, i.e what algorithm went wrong etc. But I don't think you need to go in to such depth
for the exam. Just remember that to use binary search on an array that is not sorted using natural order,you need
to use the comparator that was used to sort the array, otherwise the result will be unpredictable.

Martin

Roel De Nijs
Sheriff
Posts: 10593
143
Hi Erap,

Martin is spot-on and why it returns -1 is not explained, not in the K&B-book, not in the javadoc of the binarySearch-method. It just states that the result is undefined when the array is not sorted (or sorted with another comparator).

Kind regards,
Roel