Possible Duplicate:
Arrays.binarySearch doesnt work like it should
From my understanding of BinarySearch, it would only return an insertion point IF the element is not found in the array or collection.
So this code has me a little confused:
import java.util.*;
public class LookinGlass {
public static void main(String args[]){
String[] asa = {"x", "c", "b", "d"};
int x = Arrays.binarySearch(asa, "b");
System.out.println("Index is at " + x);
Arrays.sort(asa);
int y = Arrays.binarySearch(asa, "b");
System.out.println(x + " " + y);
}
}
When I print out x, why does it say that the index is at -1, when clearly “b” exists in the array and can be found?
Thanks
The Binary Search algorithm assumes that it is looking at data sorted in ascending order, in your first call the array:
is not sorted. Because of this the
Arrays.binarySearch(asa, "b");call is returning-1because it could not find"b"in your array using the Binary Search algorithm.