Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Arrays.BinarySearch require that the array is sorted in ascending order

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?

like image 785
ziggy Avatar asked Dec 17 '22 05:12

ziggy


2 Answers

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!).

like image 174
Oliver Charlesworth Avatar answered Apr 06 '23 03:04

Oliver Charlesworth


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.

like image 20
Peter Lawrey Avatar answered Apr 06 '23 03:04

Peter Lawrey