插值查找方法是在二分法相同方法的基础上进行了一个优化
代码如下
package 插值查找;
import java.util.Arrays;
import java.util.Scanner;
public class Display {
public int interpolation(int a[],int b){
int mid,low=1,high;
high=a.length-1;
while(low<=high)
{
mid=low+(high-low)*(b-a[low])/(a[high]-a[low]); //区分在于此处其他与二分法一样
if(b<a[mid])
{
high=mid-1;
}
else if(b>a[mid])
{
low=mid+1;
}
else
{
return mid+1;
}
}
return 0;
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Display s=new Display();
int []a=new int[5];
int b;
for(int i=0;i<a.length;i++) {
a[i]=in.nextInt();
}
Arrays.sort(a);
b=in.nextInt();
System.out.println(s.interpolation(a, b));
}
}