Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login

# Insertion Point Question on binarySearch()

Ranch Hand

Joined: Nov 08, 2006
Posts: 92

Results are:

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

Why "-1"?

SCJP with 98% by...
Martin Sergeant
Greenhorn

Joined: May 20, 2003
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

Joined: Jul 19, 2004
Posts: 8384

38

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

SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
OCAJP 7