差值查找前提 查找的序列需要有序 线性分布效率很高
理解 :二分查找的优化 二分除法 改成mid=low+(key-a[low])/(a[high]-a[low])*(high-low) 就是按照差值比例去查找
照搬一下二分的代码 运行并对比
//test
private static void search(int[] arr, int value)
{
if(arr == null || arr.length == 0)
{
return;
}
//输出结果 和耗费时间
long startTime = System.currentTimeMillis();
int index = binarySearch(arr, value, 0, arr.length > 1 ? arr.length - 1 : 0);
System.out.printf("value in arr index " + index + "\r\n");
System.out.printf("binary cost" + (System.currentTimeMillis()-startTime) + "\r\n");
startTime = System.currentTimeMillis();
int index2 = search(arr, value, 0, arr.length > 1 ? arr.length - 1 : 0);
System.out.printf("value in arr index2 " + index2 + "\r\n");
System.out.printf("binary cost" + (System.currentTimeMillis()-startTime) + "\r\n");
}
二分算法
private static int binarySearch(int[] arr, int value, int h, int t)
{
if(t < h) return -1;
int binary = (h + t) / 2;
if(arr[binary] == value) return binary;
else if(arr[binary] > value ) return binarySearch(arr, value, h, binary - 1);
else return binarySearch(arr, value, binary + 1, t);
}
差值差值
private static int search(int[] arr, int value, int h, int t)
{
if(t < h) return -1;
**int binary = h+(t-h)*((value-arr[h])/(arr[t]-arr[h]));**
if(arr[binary] == value) return binary;
else if(arr[binary] > value ) return binarySearch(arr, value, h, binary - 1);
else return binarySearch(arr, value, binary + 1, t);
}
输入
输出
输入
输出