Reputation: 5655
Here is the simple piece of code that I build to understand Arrays.binarySearch
. But it is returning a result which I did not even expect.
String[] c = {"A", "Z", "B"};
Arrays.sort(c, new MyNewComparator1()); //Z, B, A
System.out.println(Arrays.binarySearch(c, "Z")); //0
System.out.println(Arrays.binarySearch(c, "S")); //-2 based on insertion point
System.out.println(Arrays.binarySearch(c, "N")); //Unpredicable result we can expect
Here is my custom Comparator
class MyNewComparator1 implements Comparator<String> {
public int compare(String s1, String s2) {
return s2.compareTo(s1);
}
}
Result I am expecting 0, -2, Unpredictable
But the result it is returning -4, -4, -4
Can someone please help me to understand why it is returning -4
for all the search?
Thanks
Upvotes: 1
Views: 299
Reputation: 31269
As the Javadoc states, your array must be:
The array must be sorted into ascending order according to the natural ordering of its elements (as by the
sort(Object [])
method) prior to making this call.
The sort(Object [])
method that the above refers to clarifies:
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements.
You need to sort in ascending order but you are sorting in descending order.
You need to change your comparator to make it sort in ascending order:
class MyNewComparator1 implements Comparator<String> {
public int compare(String s1, String s2) {
return s1.compareTo(s2); // <-- swap s1 and s2
}
}
There is an alternative solution. You can redefine what ascending means by passing your own Comparator to the binarySearch
method call as the last argument. If you do that, then don't change the comparator - leave it as you originally posted it. But change the binarySearch
method calls:
MyNewComparator1 comparator = new MyNewComparator1();
System.out.println(Arrays.binarySearch(c, "Z", comparator)); // 0
System.out.println(Arrays.binarySearch(c, "S", comparator)); // -2 based on insertion point
System.out.println(Arrays.binarySearch(c, "N", comparator)); // Unpredicable result we can expect
Upvotes: 7