Collections.binarySearch() in Java

后端 未结 4 2108
攒了一身酷
攒了一身酷 2020-12-19 13:45

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

相关标签:
4条回答
  • 2020-12-19 14:20

    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.

    0 讨论(0)
  • 2020-12-19 14:25

    You must either sort in ascending order (per the documentation of Collections.binarySearch), or pass the custom comparator as the third parameter.

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

    Failure to do this will cause undefined results.

    0 讨论(0)
  • 2020-12-19 14:28

    Apart from the need for the list being sorted, binary Search

    returns the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1)

    (Javadoc)

    Ie: a negative index designates the negative of the index at which the item being searched would be placed if it were present, minus 1.

    I.e.

    -1 means it would be placed at index 0

    -6 means it would be placed at index 5.

    0 讨论(0)
  • 2020-12-19 14:29

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

    As results you will have:

    [2, 10, 30, 50, 100]
    Found at index 3
    
    0 讨论(0)
提交回复
热议问题