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

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

问题描述

我很抱歉这个愚蠢的问题,我一直在寻找如何像这样在我的 ArrayList 中使用二进制搜索:

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天全站免登陆