Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 456
ab_dev86 Avatar asked Mar 18 '26 14:03

ab_dev86


1 Answers

"Undefined" does not mean "will definitely give you the wrong result", or "will definitely crash".

like image 157
Oliver Charlesworth Avatar answered Mar 20 '26 13:03

Oliver Charlesworth