I am trying to create a program that does a binary search of array of randomly generated doubles and when I try to run the code, I get this error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 9999 out of bounds for length 9999
at Search.binarySearch(Search.java:34)
at Search.main(Search.java:17)
I tried changing the array size and making it smaller and bigger, but I always get a error. I don't know what less I can do. Here is the code.
import java.lang.Math;
import java.util.Arrays;
import java.util.Random;
class Search{
public static void main(String [] args){
double [] array2 = new double [9999];
for(int i = 0; i <array2.length;i++){
array[i] = (double) (Math.random() * 9999);
}
Arrays.sort(array);
System.out.println(binarySearch(array, new Random().nextDouble(9999)));
}
public static int binarySearch(double [] array, double find){
int first = 0;
int last = array.length;
int mid = (first + last ) / 2;
while(first <= last){
if(array[mid] < last){
first = mid +1;
}else if(array[mid] == find){
return mid;
}else{
last = mid -1;
}
mid = (first + last) / 2;
}
if(first > last){
return -1;
}
return -1;
}
}
How it is supposed to work that it takes the array of doubles and a random number to find if the number is in the array, if it is returns the index, if its not in the array, it returns -1. I have a linear search method that works but for some reason this won't work. Thank you