Hyosoka Poipo Hyosoka Poipo - 1 year ago 75
Java Question

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

The problem is when I use :

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

Answer Source

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