Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 716
davidx1 Avatar asked Aug 31 '26 17:08

davidx1


1 Answers

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.

like image 69
codaddict Avatar answered Sep 02 '26 07:09

codaddict



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!