java Arrays.binarySearch fails to find target

user437630 picture user437630 · Sep 9, 2010 · Viewed 10.2k times · Source
String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};   

// Search for the word "cat" 
int index = Arrays.binarySearch(sortedArray, "Quality");  

I always get -3. Problem is in "Name". Why I can not have "Name" in my array? Any idea?

Answer

Bart Kiers picture Bart Kiers · Sep 9, 2010

In order to use binarySearch, you will need to sort the array yourself first:

String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};   

java.util.Arrays.sort(sortedArray);

int index = Arrays.binarySearch(sortedArray, "Quality");