Collections.binarySearch() in Java

user9608350 :

I'm using the binarySearch() method to find the position of an element in the list. And I don't understand why the index is -6. I see that the element is at the position 1 after sorting in descending order. Can somebody tell me why I see the position -6? Thank you!

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test
{
    public static void main(String[] args)
    {
        List<Integer> al = new ArrayList<>();
        al.add(100);
        al.add(30);
        al.add(10);
        al.add(2);
        al.add(50);

        Collections.sort(al, Collections.reverseOrder()); 
        System.out.println(al);

        int index = Collections.binarySearch(al, 50);

        System.out.println("Found at index " + index);
    }
}

The output is: [100, 50, 30, 10, 2]

Found at index -6

Yassin Hajaj :

The list must be ordered into ascending natural order otherwise the results are unpredictable.

From the Javadoc

Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(java.util.List) method) prior to making this call. If it is not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.


Now, if you really want to know why the result is -6, you have to know how the method works internally. It takes the mid index and checks wether it's greater or smaller than the value you're searching for.

If it's greater (which is the case here), it takes the second half and does the same computation (low becomes middle, and max stays max).

At the end, if the key is not found, the method returns -(low + 1) which in your case is -(5 + 1) because the max index becomes the low when there is no way to split it further.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=473741&siteId=1