davidx1
davidx1

Reputation: 3673

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

I am a beginner in Java and is learning to use array. I understand that when using the binary search method of Array, it will return a negative number if the entry is not found. However, in the following code, I am getting a negative number returned for 9, 10, and 11.

I am wondering if anyone could help point out what I am doing wrong? thanks!

   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 output i get are:

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

Any help would be much appreciated.

Upvotes: 3

Views: 6168

Answers (3)

The Tran
The Tran

Reputation: 470

Please keep in mind that to make Array.binarySearch(array, key) method work correctly the source array must be sorted before. If the source array is not sorted, the result will be undefined. From your question, the source array is not sorted. To sort array in natural order you use the util method Arrays.sort(array). You can also provide an additional 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);
    }
});

Upvotes: 0

Roadie
Roadie

Reputation: 1

The negative refers the component-1 where the String would be found / inserted int your array, and comes up because your array not being sorted. The element is not being found. so for your array "9" being -17 that it will be inserted into component 16 "10" would be inserted into component 1 "11" would be inserted into component 1

Type of Array doesn't matter as the Arrays methods have been overloaded.

sort by Using

Arrays.sort(oneToSixteen);

then use your binarySearch()

Upvotes: 0

codaddict
codaddict

Reputation: 455020

This is because your array is an an array of String and not int and it is not sorted.

The documentation clearly states that the array being searched must be sorted and if it isn't the results are undefined.

To sort the array you can use the sort method of the Arrays class.

Upvotes: 9

Related Questions