Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java binarysearch algo on descendant list

Tags:

java

list

In Java Collections.binarysearch() works for sorted list with ascending order. Is there an easy way to have a binarysearch for a list with descending order ?

Changing the list is not an option

like image 746
ic3 Avatar asked Oct 26 '11 20:10

ic3


2 Answers

There's an overload of binarySearch() that accepts a custom Comparator. Call that one, passing in a comparator that reverses the ordinary comparison outcomes.

For example, if you have a List<Integer>, then call:

int index = Collections.binarySearch<Integer>(
             intList, Integer.valueOf(1), Collections.reverseOrder());

(Use of `Collections.reverseOrder() thanks to @MarkPeters.)

like image 67
dlev Avatar answered Nov 16 '22 15:11

dlev


Use Guava's Lists#reverse() to create a reversed view of the list, and pass the view into Collections#binarySearch(). The index in the original list is the list's length minus the value returned by binarySearch().

like image 3
Matt Ball Avatar answered Nov 16 '22 13:11

Matt Ball