In Java, why does this return a negative number when searching for an array with a binary search?

I am new to Java and am involved in using an array. I understand that when using the Array binary search method, it returns a negative number if the record is not found. However, in the following code, I get a negative number returned for 9, 10 and 11.

I am wondering if anyone can help indicate what I am doing wrong? thank you

   String [] oneToSixteen = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"};

   System.out.println("Searching for 7: "+ Arrays.binarySearch(oneToSixteen, "7"));
   System.out.println("Searching for 8: "+ Arrays.binarySearch(oneToSixteen, "8"));
   System.out.println("Searching for 9: "+ Arrays.binarySearch(oneToSixteen, "9"));
   System.out.println("Searching for 10: "+ Arrays.binarySearch(oneToSixteen, "10"));
   System.out.println("Searching for 11: "+ Arrays.binarySearch(oneToSixteen, "11"));

The conclusion I get is:

Searching for 7: 6
Searching for 8: 7
Searching for 9: -17
Searching for 10: -2
Searching for 11: -2

Any help would be greatly appreciated.

+3
source share
3 answers

This is because your array is an array Stringand not intand is not sorted .

, , undefined.

, Arrays.

+9

-1, String / , . . "9" - -17, 16 "10" 1 "11" 1

, .

Arrays.sort(oneToSixteen);

()

0

Please keep in mind that for the method to execute correctly, the Array.binarySearch(array, key)source array must be sorted earlier. If the original array is not sorted, the result will be undefined. From your question, the original array is not sorted. The utility method is used to sort the array in the natural order Arrays.sort(array). You can also provide an optional comparator to control the sort order Arrays.sort(array, comparator).

Example:

// sort in natural order (ascending)
Arrays.sort(oneToSixteen);

// sort descending using comparator
Arrays.sort(oneToSixteen, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1);
    }
});
0
source

All Articles