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.
source
share