Collections.binarySearch() in Java

后端 未结 4 2129
攒了一身酷
攒了一身酷 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.

提交回复
热议问题