插补搜寻法 类似于折半查找,不同的是插补查找使用的是按照比例来选择对比项
public class ISearch {
public static int Max = 20;
public static int[] Data = { 12, 16, 19, 22, 25, 32, 39, 48, 55, 57, 58,
63, 68, 69, 70, 78, 84, 88, 90, 97 }; // 数据数组
public static int Counter = 1; // 计数器
public static void main(String args[])
{
int KeyValue = 32;
// 调用插补查找
if (InterpolationSearch(KeyValue))
{
// 输出查找次数
System.out.println("");
System.out.println("Search Time = " + (int) Counter);
}
else
{
// 输出没有找到数据
System.out.println("");
System.out.println("No Found!!");
}
}
// ---------------------------------------------------
// 插补查找法
// ---------------------------------------------------
public static boolean InterpolationSearch(int KeyValue)
{
int Low; // 插补查找法左边界变量
int High; // 插补查找法右边界变量
int Middle; // 插补查找法中间数
Low = 0;
High = Max - 1;
Middle = Low + (KeyValue - Data[Low]) * (High - Low)
/ (Data[High] - Data[Low]);
if (Middle < Low)
Middle = Low;
if (Middle > High)
Middle = High;
while (Low <= High)
{
if (KeyValue < Data[Middle]) // 欲查找值较小
High = Middle - 1; // 查找前半段
// 欲查找值较大
else if (KeyValue > Data[Middle])
Low = Middle + 1; // 查找后半段
// 查找到数据
else if (KeyValue == Data[Middle])
{
System.out.println("Data[" + Middle + "] = " + Data[Middle]);
return true;
}
if (Low < High)
Middle = Low + (KeyValue - Data[Low]) * (High - Low)
/ (Data[High] - Data[Low]);
if (Middle < Low)
Middle = Low;
if (Middle > High)
Middle = High;
Counter++;
}
return false;
}
}