Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Output for Arrays.binarySearch()

 
Harikrishna Gorrepati
Ranch Hand
Posts: 423
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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, c.compare(e1, 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.

Parameters:
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.
Throws:
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
Greenhorn
Posts: 18
Chrome Java Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Jim
 
Imad Aydarooos
Ranch Hand
Posts: 87
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only you have to pass the same compartor to the sort and to the binary search as the following
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic