views:

186

answers:

4

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Arrays.html

Sun does not mention any complexity for their binary-search implemention. Is this a mistake? I know it should be O(logn), but it makes me nervous when they don't state this explicitly. They do for some of their algoritms, like Arrays.sort.

Does any of you have any knowledge of the actual implementation? I have not had the opportunity to download the source code yet myself! I guess its a trivial binary search, but Sun do sometimes tweak the algoritms for better performance.

+3  A: 

binary search is by definition O(log n) (on average) guess there's no need to mention it explicittly.

leeeroy
Looking at the code even if the array is unsorted apparently it cannot be worse than O(log n).
Webinator
@WizardOfOdds - but you'll probably get the wrong answer, of course.
Stephen C
If the array is unsorted the doco says explicitly that the result is undefined.
Software Monkey
+1  A: 

Arrays.sort is guaranteed to return a sorted array, no matter what your array contains.

Arrays.binarySearch(...) (lowercase 'b' btw) cannot guarantee anything seen that your array may be unsorted.

Now editing my answer: looking at the code apparently it's not possible to perform worse than O(log n). But there's of course no guarantee that you'll have found the correct value.

Webinator
A: 

Does any of you have any knowledge of the actual implementation?

You can find the source code of the actual implementation yourself in your JDK installation, or using a Google search. For example, search for "java.util.Arrays.java.html".

But I have no doubt that the binarySearch methods are O(logN). If they weren't somebody would have noticed ... in the last 10 or so years.

Stephen C
+1  A: 

The implementation of java.util.Array is straightforward and there is no room for optimizations.

You find the source code in JAVA_HOME/src.zip. The sorting alogrithm in this class, which is required in order to use binary search, is a optimized quicksort wich offers n*log(n) performance (on many data sets).

stacker
"The sorting alogrithm in this class, which is required in order to use binary search ...". To be clear, you are **not** required to use `Array.sort(...)`. You can ensure that the array is ordered using any technique that works!!
Stephen C
Thanks, this was inaccurately
stacker
What does the complexity of the sorting algorithm have to do with the complexity of `binarySearch` anyway? I can just as well sort using a bubble sort and then find elements in O(log n) using `binarySearch`.
MAK
In order to use binary search the array must be sorted, since I actually looked in the source, I just added this info.
stacker