I am trying to do a binary search in a method on an array of numbers randomly filled with 0 to 100 for each number. I am searching for the number in the array but I keep getting multiple errors when I run the program.
public static void binarySearch(int[] array){
Arrays.sort(array);
int searchComparisons = 0;
int lower = array[0];
int upper = array[array.length - 1];
for (int i = 0; i<array.length; i++){
System.out.println("Element "+i+" is " +array[i]);
}
int testSubject = (array[0]+array[array.length-1])/2;
while((array[testSubject] != 99) && (lower <= upper)){
searchComparisons++;
if (array[testSubject] > 99){
upper = testSubject - 1;
}
else{
lower = testSubject + 1;
}
testSubject = (lower + upper) / 2;
}
if (lower <= upper){
System.out.println("Binary search - number of comparisons " +searchComparisons);
System.out.println("This index = "+testSubject);
}
else{
System.out.println("Linear search - number of commparisons: " +searchComparisons);
System.out.println("Number not found");
}
}
The errors are:
java.lang.ArrayIndexOutOfBoundsException: 50
at SearchArray.binarySearch(SearchArray.java:49)
at SearchArray.main(SearchArray.java:82)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)