Below program returns search index as -1.The binarySearch should return the location of '50' in the List. However it returns the index as -1.
package com.core.java.collections;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CollectionsBinarySearch {
public static void main(String[] args) {
List<Integer> al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
al.add(50);
// The last parameter specifies the comparator
// method used for sorting.
int index = Collections.binarySearch(
al, 50, Collections.reverseOrder());
System.out.println("Found at index " + index);
}
}
To use Collection.binarySearch()
, your data must be sorted by given given comparator. If it is not, then the output will be undefined.
You have given comparator Collections.reverseOrder()
, so your data must be sorted in Collections.reverseOrder()
So before binarySearch if you do
Collections.sort(al, Collections.reverseOrder());
and then apply it your answer will be
Found at index 0
which is correct, as data will be : 50,40,30,20,10.