简体   繁体   English

使用ArrayList的binarySearch集合

[英]binarySearch collections using ArrayList

I'm sorry for the stupid question, I have been searching about how to use binarysearch with my ArrayList like this : 我为这个愚蠢的问题感到抱歉,我一直在搜索如何将binarysearch与我的ArrayList结合使用,如下所示:

List<Integer> arrList = new ArrayList<Integer>();       
        arrList.add(3); 
        arrList.add(5); 
        arrList.add(7);
        arrList.add(2);

The problem is when I use : 问题是当我使用时:

Collections.sort(arrList);
Collections.reverse(arrList);
int indeks = Collections.binarySearch(arrList, 7);

the value of indeks is always -5, I thought it should be 2 because after reversing myArrList the output looks like this : indeks的值始终为-5,我认为应该为2,因为在反转myArrList之后,输出看起来像这样:

[7, 5, 3, 2]

So what should I do here in order to get the right indeks of 7...? 那么,在这里我该怎么做才能获得7的正确负债? Thanks in advance 提前致谢

Collections.binarySearch() expects elements to be in ascending order: Collections.binarySearch()期望元素按升序排列:

The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. 在进行此调用之前,必须根据列表元素的自然顺序将其按升序排序(例如通过sort(List)方法)。 If it is not sorted, the results are undefined. 如果未排序,则结果不确定。

If you want to do a binary search on a descending list, use Comparator.reverseOrder() : 如果要对降序列表进行二进制搜索,请使用Comparator.reverseOrder()

int indeks = Collections.binarySearch(arrList, 7, Comparator.reverseOrder());

indeks is now 0, corresponding to the first element of the list. 现在indeks为0,对应于列表的第一个元素。

Note that you can use the same comparator to sort the list descending, instead of sorting ascending and then reversing: 请注意,您可以使用相同的比较器对列表进行降序排序,而不是先升序然后倒序:

Collections.sort(arrList, Comparator.reverseOrder());

binarySearch() results are undefined if the list is not sorted in ascending order. 如果列表未按升序排序,则binarySearch()结果不确定。 By reversing your list, it's sorted in descending order, hence the results you're seeing. 通过反转您的列表,它以降序排序,因此您看到的是结果。

From the Javadoc : Javadoc

The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. 在进行此调用之前,必须根据列表元素的自然顺序将其按升序排序(例如通过sort(List)方法)。 If it is not sorted, the results are undefined. 如果未排序,则结果不确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM