File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Output for Arrays.binarySearch() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Output for Arrays.binarySearch()" Watch "Output for Arrays.binarySearch()" New topic

Output for Arrays.binarySearch()

Harikrishna Gorrepati
Ranch Hand

Joined: Sep 23, 2010
Posts: 423
Hi Jim, I have seen the Javadocs. They never mentioned natural ordering/ascending order.It says as given below..Please advice what is happening here..

public static <T> void sort(T[] a,
Comparator<? super T> c)

Sorts the specified array of objects according to the order induced by the specified comparator. All elements in the array must be mutually comparable by the specified comparator (that is,, e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance.

a - the array to be sorted
c - the comparator to determine the order of the array. A null value indicates that the elements' natural ordering should be used.
ClassCastException - if the array contains elements that are not mutually comparable using the specified comparator.

Jim Ronholm wrote:... but the answer is simply that your Comparator causes the arrays to be sorted into descending order "according to the natural ordering of its elements", not ascending.
Jim Ronholm

Joined: Nov 15, 2002
Posts: 18

I think my answer was poor.

The natural ordering is the order they would sort in if you used the built-in method. Your Comparator causes them to be in reverse order. When the binary search uses the built-in to test a value it checks to see if the key is smaller or larger than the current test. If it is smaller then it discards/ignores all the values that are higher and vice versa. But because your array is in reverse order (for the built-in method) it discards/ignores the wrong data.

Imad Aydarooos
Ranch Hand

Joined: Nov 02, 2010
Posts: 87
Only you have to pass the same compartor to the sort and to the binary search as the following

love demgracy, knowledge demogracy, open source and Java - OCPJP 76%
I agree. Here's the link:
subject: Output for Arrays.binarySearch()
jQuery in Action, 3rd edition