使用ArrayList的binarySearch集合 [英] binarySearch collections using ArrayList

查看:596
本文介绍了使用ArrayList的binarySearch集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉这个愚蠢的问题,我一直在搜索如何在我的ArrayList中使用binarysearch,如下所示:

I'm sorry for the stupid question, I have been searching about how to use binarysearch with my ArrayList like this :

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

问题在于我使用时:

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

indeks的值总是-5,我认为它应该是2,因为在反转myArrList之后输出看起来像这样:

the value of indeks is always -5, I thought it should be 2 because after reversing myArrList the output looks like this :

[7, 5, 3, 2]

那么我该怎么做才能获得正确的7 ...?
提前致谢

So what should I do here in order to get the right indeks of 7...? Thanks in advance

推荐答案

Collections.binarySearch() 期望元素按升序排列:

Collections.binarySearch() expects elements to be in ascending order:


列表必须根据元素的自然顺序按升序排序(如在进行此调用之前,通过 sort(List)方法)。如果未排序,则结果未定义。

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. If it is not sorted, the results are undefined.

如果要在降序列表上进行二分查找,请使用 Comparator.reverseOrder()

If you want to do a binary search on a descending list, use Comparator.reverseOrder():

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

indeks 现在为0,对应于列表的第一个元素。

indeks is now 0, corresponding to the first element of the list.

请注意,您可以使用相同的比较器对列表降序进行排序,而不是按升序排序然后反转:

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

这篇关于使用ArrayList的binarySearch集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆