I wanted to clarify that why is search result with and without comparator same, when the array searched is :
String [] sa = {"one", "two", "three", "four", "1", "2"}; //2 as compared to
String [] sa = {"one", "two", "three", "four"}; //1
In first case it doesn't matter whether comparator is passed in binary search. I wanted to clarify why is it happening that way?
class SearchObjArray {
public static void main(String args[]) {
//String [] sa = {"one", "two", "three", "four"}; // 1
String [] sa = {"one", "two", "three", "four", "1", "2"}; // 2
Arrays.sort(sa);
for (String s : sa)
System.out.print(s + " ");
System.out.println("\none = " + Arrays.binarySearch(sa, "one"));
System.out.println("now reverse sort");
ReSortComparator rs = new ReSortComparator();
Arrays.sort(sa, rs);
for (String s : sa)
System.out.print(s + " ");
System.out.println("\none = " + Arrays.binarySearch(sa, "one"));
System.out.println("one = " + Arrays.binarySearch(sa, "one", rs));
}
static class ReSortComparator implements Comparator<String> {
public int compare(String a, String b) {
return b.compareTo(a);
}
}
}
if case //1 is run the results are as mentioned in the book but when case //2 is run I get following results:
1 2 four one three two
one = 3
now reverse sort
two three one four 2 1
one = 2
one = 2
Thanks