According to the documentation:
public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)
Searches the specified array for the specified object using the binary search algorithm.
The array must be sorted into ascending order according to the specified comparator (as by the sort(T[], Comparator) method) prior to making this call.
If it is not sorted, the results are undefined. If the array contains multiple elements equal to the specified object, there is no guarantee which one will be found.
Does the above mean that the Arrays.binarySearch
method can only be used 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:
i h f e c b a
-5
-5 puts the insertion point at the element with value c which is correct. (i.e. -4-1).
Why is the documentation saying that the array must be sorted in ascending order?
It says "must be sorted into ascending order according to the specified comparator". The part in bold is the crucial part; your array is indeed sorted according to the specified comparator (because you just sorted it!).
It requires all the element be increasing based on how Comparator is implemented. e.g. you use a reverse Comparator, all the elements have to be in reverse order.
Why is the documentation saying that the array must be sorted in ascending order?
A binary search works based on this assumption. http://en.wikipedia.org/wiki/Binary_search_algorithm When it compares the middle element it can assume that if its greater than that element it is greater than all the elements before the middle as well. If the array was in no particular order it would have to search the entire array, also called a brute force search.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With