Search code examples
javaarraysbinary-search

Java Arrays binarySearch


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?


Solution

  • "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:

    • enter binary search with first = 0, last = 4, middle = 2 compare
    • array[middle] with "eee" ("bbb"<"eee") => first = 2 + 1; middle = 3;
    • compare array[middle] with "eee" => "found" ; return 3;