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
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.)
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With