aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Insertion Point Question on binarySearch() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Insertion Point Question on binarySearch()" Watch "Insertion Point Question on binarySearch()" New topic
Author

Insertion Point Question on binarySearch()

Erap Estrada
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
Bartender

Joined: Jul 19, 2004
Posts: 5406
    
  13

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
http://www.javaroe.be/
Erap Estrada
Ranch Hand

Joined: Nov 08, 2006
Posts: 92
Great. Thanks guys for the clarification.
 
 
subject: Insertion Point Question on binarySearch()