Maryadi Poipo
Maryadi Poipo

Reputation: 1478

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

Upvotes: 1

Views: 569

Answers (2)

shmosel
shmosel

Reputation: 50716

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

Upvotes: 2

Robby Cornelissen
Robby Cornelissen

Reputation: 97130

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.

Upvotes: 0

Related Questions