java Arrays.binarySearch fails to find target

7

String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};   

// Search for the word "cat" 
int index = Arrays.binarySearch(sortedArray, "Quality");  

I always get -3. Problem is in "Name". Why I can not have "Name" in my array? Any idea?

user437630

Posted 2010-09-09T06:06:47.173

Reputation: 72

1"Name" should be before "Quality", and "Package" should be before "Testing". – Jon Skeet – 2010-09-09T06:09:25.863

1binarySearch is only for sorted array. – 卢声远 Shengyuan Lu – 2010-09-09T06:12:51.267

@Jon, I think you meant that "Package" should come before "Quality". – Bart Kiers – 2010-09-09T07:11:33.493

Answers

25

In order to use binarySearch, you will need to sort the array yourself first:

String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};   

java.util.Arrays.sort(sortedArray);

int index = Arrays.binarySearch(sortedArray, "Quality");  

Bart Kiers

Posted 2010-09-09T06:06:47.173

Reputation: 130 123

6

The array is must be sorted. From Javadoc of binarySearch():

The range must be sorted into ascending order according to the natural ordering of its elements prior to making this call. If it is not sorted, the results are undefined.

Jeffrey

Posted 2010-09-09T06:06:47.173

Reputation: 966

2

An array must be sorted for binary search to work. The javadoc for binarySearch says this:

The array must be sorted into ascending order according to the natural ordering of its elements (as by the sort(Object[]) method) prior to making this call. If it is not sorted, the results are undefined.

(Emphasis added.)

And the reason is simple. The binary search algorithm has a precondition that the input array is sorted.

Stephen C

Posted 2010-09-09T06:06:47.173

Reputation: 509 237