Friday, 27 September 2013

Strange output for Binary Search when result is not found

Strange output for Binary Search when result is not found

I am getting a strange output when the result is not found.
import java.util.Arrays;
import java.util.Comparator;
public class BinarySearch {
public static void main(String args[]) {
String arr[] = { "c", "a", "e", "f", "z" };
MySort ms = new MySort();
Arrays.sort(arr, ms);
for (String c : arr) {
System.out.println(c);
}
System.out.println(Arrays.binarySearch(arr, "b", ms));
}
static class MySort implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
}
}
Output: z f e c a -6
Why does it print -2 when i pass "y" as my query param and -5 when i pass
b. Can anyone let me know what is happening if the result is not found.

No comments:

Post a Comment