简体   繁体   中英

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 :

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 :

[7, 5, 3, 2]

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

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

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.

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

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

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

binarySearch() results are undefined if the list is not sorted in ascending order. By reversing your list, it's sorted in descending order, hence the results you're seeing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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