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.
This is because your array is an an array of
Stringand notintand 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.