Does Arrays.BinarySearch require the array to be sorted in ascending order

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?

+4
source share
3 answers

Each comparator determines the order on the elements of this type. The requirement is only that the elements of the array must be sorted so that a [0] ... <a [n-1] for some correct definition of <. This definition should not correspond to our generally accepted notion of <for example. numbers - indeed, it could even be defined as normal>.

+3
source

He says that "must be sorted in ascending order according to the specified comparator ." The bold part is an important part; your array is really sorted according to the specified comparator (because you just parsed it!).

+5
source

The entire element is required to increase depending on how the comparator is implemented. for example, you use a reverse comparator, all elements must be in reverse order.

Why does the documentation indicate that the array should be sorted in ascending order?

Binary search works based on this assumption. http://en.wikipedia.org/wiki/Binary_search_algorithm When he compares the middle element, he can assume that if it is larger than this element, it is larger than all the elements to the middle, If the array was not in a certain order, it would have to search the entire array, also called brute force search.

+4
source

Source: https://habr.com/ru/post/1388971/


All Articles