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?
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.
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 .
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With