Java binarysearch algo in child list

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

List change is not an option

+4
source share
2 answers

Here's the overload of binarySearch() , which accepts a custom Comparator . Call it by going to a comparator that changes the usual comparison results.

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

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

(Using `Collections.reverseOrder () thanks @MarkPeters.)

+5
source

Use Guava Lists#reverse() to reverse the list and pass the view to Collections#binarySearch() . The index in the source list is the length of the list minus the value returned by binarySearch() .

+3
source

All Articles