Reputation:
I am currently trying to implement interpolation search with floating numbers, here is my code:
import java.util.Arrays;
class InterpolationSearch {
private static float comparisions = 0;
public static int interpolationsearch (double arr[], double x, int high, int low) {
while ( low<=high) {
comparisions++;
int i = low + (x-arr[low])*(high-low)/(arr[high]-arr[low]);
if (x==arr[i])
return i;
else if (x<arr[i])
high = i-1;
else
low = i+1;
}
return -1;
}
public static void main(String args[]) {
int n=100;
double array[] = new double[n];
for (int i=0; i<100; i++) {
for (int k=0; k<n; k++) {
double r = Math.random();
r = r * 100;
r = Math.round(r);
r = r / 100;
array[k] = r;
}
Arrays.sort(array);
double search = Math.random();
search = search*100;
search = Math.round(search);
search = search/100;
int result=interpolationsearch(array, search, n-1, 0);
if (result == -1)
System.out.println(search +" befindet sich nicht im Array.");
else
System.out.println(search+" befindet sich im Array an der Stelle "+(result)+".");
}
System.out.println("Anzahl der gemittelten Vergleiche: "+comparisions/100+".");
}
}
First of all is my algorithm correct? Second how do I get this working with floating numbers? In the current code I get the following error at line 8: Type mismatch: cannot convert from double to int. I already tried to cast everything to int, but it did not work.
Upvotes: 1
Views: 579
Reputation: 1144
2nd Answer is typecast correctly.
int i = (int)(low + (x-arr[low])*(high-low)/(arr[high]-arr[low]));
Now your programme is giving following output
0.47 befindet sich im Array an der Stelle 41.
0.33 befindet sich im Array an der Stelle 32.
1.0 befindet sich im Array an der Stelle 99.
0.52 befindet sich im Array an der Stelle 54.
0.51 befindet sich im Array an der Stelle 48.
0.32 befindet sich im Array an der Stelle 25.
Now you have to explain it more about what do you want to achieve. Is this the correct output?
Upvotes: 1
Reputation: 48297
is my algorithm correct?
you are the one that can verify if the algo. is working...
I already tried to cast everything to int, but it did not work
it works! you just need to cast the result of the whole operation in order to convert a double to int but remember you will lost the decimal part..
example:
int i = (int) (low + (x - arr[low]) * (high - low) / (arr[high] - arr[low]));
Upvotes: 0