Updated: I am trying to use Collections.sort() to sort an arrayList with a comparator parameter. Then do binarysearch.
package collection;
import java.util.*;
public class TryBinarySearch {
public static void main(String[] args){
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 100; i++)
list.add(i);
System.out.println(list);
int b = Collections.binarySearch(list, 8);
System.out.println(b); // a is 8 as expected.
Collections.shuffle(list);
System.out.println(list);
Collections.sort(list, new
Comparator<Integer>(){
public int compare(Integer a, Integer b){
return b.intValue() - a.intValue();
}
});
System.out.println(list); //list is reversed as expected.
int a = Collections.binarySearch(list, 8);
System.out.println(a); // why a is -1?
}
}
b is 8 as expected; I made a reverse sorting. My question is why a is -1, instead of 92?
Binary search only works when the list is already sorted. The way that binary search works is that the algorithm assumes that if the value at its "guess" index is higher than the one we're looking for, the actual index must be lower - and vice versa.
If the collection isn't sorted, that assumption doesn't hold, so the algorithm fails.
The documentation states this very clearly:
The list must be sorted into ascending order according to the specified comparator (as by the
sort(List, Comparator)
method), prior to making this call. If it is not sorted, the results are undefined.
See more on this question at Stackoverflow