Issues with Arrays.binarySearch(Object[], Object)
Hi,
I am trying to find a String in an array using Arrays.binarySearch(Object[], Object). I have sorted the array initially. However i am getting negative values even if the String value is present in the array.
Is it that with String values the above method gives errorneous results.
Has anybody faced a similar problem.
Regards
[360 byte] By [
p_028774a] at [2007-10-2 21:55:32]

Which way do you sort your array?
I have tried the next code and it works:
String a1 = "a1";
String a2 = "a2";
String[] array = { "a5" , "a1", "a3" };
Arrays.sort(array);
System.out.println(Arrays.binarySearch(array, a1));
System.out.println(Arrays.binarySearch(array, a2));
I tried to do this in a small program and it seems to work fine.
String strArr[]= {"a","e","d","c","b"};
Arrays.sort(strArr);
System.out.println(Arrays.binarySearch(strArr,"d"));
Above statement prints 3.
I tried this and it seems to be working only part of the time, not sure if I am using this incorrectly?
import java.util.Arrays;
class test {
public static void main(String[] args) {
String[] names = new String[]{"BOB", "JOE", "JIMMY", "FRED"};
for(String name : names){
System.out.println(name + " is at : " +
Arrays.binarySearch(names, name)
);
}
}
}
The above test returns:
BOB is at : 0
JOE is at : 1
JIMMY is at : -2
FRED is at : -2
This from the javadocs for the binarySearch method:
Searches the specified array for the specified object using the binary search algorithm. The array must be sorted into ascending order according to the natural ordering of its elements (as by Sort(Object[]), above) prior to making this call. If it is not sorted, the results are undefined.
If the source Array is not sorted the search is not reliable.