Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Arrays.binarySearch fails to find target

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?

like image 635
user437630 Avatar asked Sep 09 '10 06:09

user437630


People also ask

How does Arrays binarySearch work in Java?

binarySearch(Object[] a, Object key) method searches the specified array for the specified object using the binary search algorithm. The array 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.

What Arrays return binarySearch?

Returns. The index of the specified value in the specified array , if value is found; otherwise, a negative number. If value is not found and value is less than one or more elements in array , the negative number returned is the bitwise complement of the index of the first element that is larger than value .

What does Java's Arrays binarySearch () method return?

binarySearch() method can look for a given element in a sorted array and return its index if found. Remember, the method returns the index of the found item and not the item itself. So you can store the index in an integer like the one used in this example.

What does binary search return if not found Java?

Arrays#binarySearch() returns the index of the element you are searching, or if it is not found, then it returns the (-index - 1) where index is the position where the element would be inserted in the sorted array.


1 Answers

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");  
like image 161
Bart Kiers Avatar answered Sep 19 '22 15:09

Bart Kiers