Collections.binarySearch () in Java

I use the binarySearch () method to find the position of an item in a list. And I do not understand why the index is -6. I see that the item is in position 1 after sorting in descending order. Can someone tell me why I see position -6? Thank!

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);
    }
}

Output: [100, 50, 30, 10, 2]

Found at index -6

+4
source share
4 answers

The list should be ordered in ascending order, otherwise the results are unpredictable.

From javadoc

. ( sort (java.util.List)) . , undefined. , , , .


, , -6, , . , , .

( ), ( , max ).

, , -(low + 1), -(5 + 1), max , .

+5

( Collections.binarySearch), .

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

undefined.

+2

,

, ; (- ( ) - 1)

(Javadoc)

Ie: , , , 1.

..

-1 , 0

-6 , 5.

+2

Yes, ascending order is important for this algorithm. Just replace the sort with Collections.sort(al).

As a result you will receive:

[2, 10, 30, 50, 100]
Found at index 3
0
source

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


All Articles