查找之差值查找

差值查找前提 查找的序列需要有序 线性分布效率很高
理解 :二分查找的优化 二分除法 改成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);
}

输入
在这里插入图片描述
输出
在这里插入图片描述

输入

在这里插入图片描述
输出
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值