简要
改进二分查找算法的mid(中间节点)的计算
设mid = (low + (high - low) *(val - R[low])/(R[high] - R[low]);
这样java二分查找算法代码,如果要查找的值的索引位于数组的边缘java二分查找算法代码,则查找效率会大大提高;
从测试结果来看:11需要搜索两次查找算法对mid(中间节点)的计算进行改进
,92只需要搜索一次;
实现代码
<p><pre>/**
- className:Search
* - @author:zjl
- @version:0.1
- @date:2020/8/1910:16
- @since:jdk1.8
*/
public class Search {
public static void main(String[] args) {
int R[] = {0,1,11,33,44,59,69,80,86,92,99};
int i = interpolationSearch(R, 0, R.length - 1, 11);
System.out.println("11的索引是:" + i);
System.out.println("--------------------------");
int i1 = interpolationSearch(R, 0, R.length - 1, 92);
System.out.println("92的索引是:" + i1);
System.out.println("--------------------------");
int i2 = interpolationSearch(R, 0, R.length - 1, 3);
System.out.println("3的索引是:" + i2);
}
/**
* 插值查找
* @param R
* @param low 数组开始索引
* @param high 数组结束索引
* @param val 查找的值
* @return 没有找到返回-1,否则返回对应索引
*/
public static int interpolationSearch(int[] R, int low, int high, int val) {
System.out.println("查找一次...");
float p = val - R[low];
float q = R[high] - R[low];
float t = p/q;
int mid = (int)(low + (high - low) * t); //与二分查找求中间节点方式不同(改进点)
if(R[low]>val||R[high]