According to the documentation:
public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)
Searches for the specified array for the specified object using a binary search algorithm.
The array must be sorted in ascending order according to (by the sorting method (T [], comparator) before making this call.
If it is not sorted, the results are undefined. If the array contains several elements equal to the specified object, there is no guarantee to be found.
Does this mean that the Arrays.binarySearch method can be used only when the array is sorted in ascending order?
I tested it as shown below
class Unturned { public static void main(String[] args) { String[] chars = {"a", "b", "c", "e","f","h","i"}; MySort ms = new MySort(); Arrays.sort(chars, ms); for(String c : chars ) System.out.print(c + " "); System.out.println("\n" + Arrays.binarySearch(chars, "d", ms)); } static class MySort implements Comparator<String> { public int compare(String a, String b) { return b.compareTo(a); } } }
output:
ihfecba -5
-5 puts an entry point in an element with a value of c, which is correct. (i.e. -4-1). Why does the documentation indicate that the array should be sorted in ascending order?
source share