Integer comparator
Posted: Tue Oct 04, 2016 7:53 am
Hi,
am a bit confused about binarySearch on Arraylist of Integers with this desc comparator (if comparator is asc things are clear to me):
public class SortandSearch{
static final Comparator<Integer> IntegerComparator=new Comparator<Integer>(){
public int compare (Integer n1, Integer n2){
return n2.compareTo(n1);
}
};
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(4);
list.add(1);
list.add(3);
list.add(2);
Collections.sort(list,IntegerComparator);
System.out.println(Collections.binarySearch(list, 3));
}
}
It returns 1. OK.
If we do System.out.println(Collections.binarySearch(list, 2));
it returns -1. Why not 2?
If I do System.out.println(Collections.binarySearch(list, 5));
it returns -5, why not -1?
Tnx.
am a bit confused about binarySearch on Arraylist of Integers with this desc comparator (if comparator is asc things are clear to me):
public class SortandSearch{
static final Comparator<Integer> IntegerComparator=new Comparator<Integer>(){
public int compare (Integer n1, Integer n2){
return n2.compareTo(n1);
}
};
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(4);
list.add(1);
list.add(3);
list.add(2);
Collections.sort(list,IntegerComparator);
System.out.println(Collections.binarySearch(list, 3));
}
}
It returns 1. OK.
If we do System.out.println(Collections.binarySearch(list, 2));
it returns -1. Why not 2?
If I do System.out.println(Collections.binarySearch(list, 5));
it returns -5, why not -1?
Tnx.