I am making a java program that uses the interpolation search below I have gotten from wikipedia. In my main program I have created an int array that will have 100,000 spots. Then I fill all those spots with random numbers and sort it. I then generate a random search key and call the function. I am also looping the function call 100 times each time with a different search key. When I do this I get an array out of bounds error on this statement if (sortedArray[mid] < toFind). The program works fine with an array with 10 spots, 100 spots, 1000 spots, but when I get to 100,000 I get the error. Do you know what I can do to fix this problem?
public int interpolationSearch(int[] sortedArray, int toFind){
// Returns index of toFind in sortedArray, or -1 if not found
int low = 0;
int high = sortedArray.length - 1;
int mid;
while (sortedArray[low] <= toFind && sortedArray[high] >= toFind) {
mid = low +
((toFind - sortedArray[low]) * (high - low)) /
(sortedArray[high] - sortedArray[low]);
if (sortedArray[mid] < toFind)
low = mid + 1;
else if (sortedArray[mid] > toFind)
// Repetition of the comparison code is forced by syntax limitations.
high = mid - 1;
else
return mid;
}
if (sortedArray[low] == toFind)
return low;
else
return -1; // Not found
}
You are overflowing the max value that can be stored in an int which is 2,147,483,647.
When calculating the numerator in your equation you are doing ((39258-0)*(99999-0)) which is 3,925,760,742.
If you change it to this you won’t have this issue:
I think you also need to change your while loop to be:
Otherwise you have a situation where sortedArray[low] == sortedArray[high] == toFind
Then your equation reduces to
Java allows division by zero. I’m not exactly sure what happens though, it may be that in this case mid = infinity or NaN.