Here is my simple piece of code, where I build a String array and try to search a string within this array:
String[] arr = new String[5];
arr[0] = "ccc";
arr[1] = "aaa";
arr[2] = "bbb";
arr[3] = "eee";
arr[4] = "ddd";
System.out.println(Arrays.binarySearch(arr,"eee"));
Taken directly from Java 6 binarySearch documentation:
The array must be sorted prior to making this call. If it is not sorted, the results are undefined
Actually, I ran my code several time getting as output always 3 which is the position of eee in my not sorted array, but the result seems not to be "undefined" as the documentation said.
What am I missing?
"Undefined" means that the algorithm will run on your array, but the result is not guaranteed to be correct (binary search strongly needs a sorted array in order to work). Your example works because this is what happens: