来源:https://www.bilibili.com/video/BV1B4411H76f?p=77
一、思路
插值法查找:序列还是需要有序,思路跟二分法是一致的,但是寻找中间坐标mid的方法不同。
对于二分法mid=1/2(low+high)=low+1/2*(high-low)
插值法中mid的求法是这样的:mid=low+((finalVal-arr[low])/(arr[high]-arr[low]))(high-low)
利用目标值finalVal的大小,大体确定一下它的位置
例如:一个1-100的数组,要找1
那二分法:mid = 0+1/2(99-0)=49,从49开始找
插值法:mid=0+((1-1)/(100-1))(99-0)=0,从0开始找,这就快了
二、实现
1 //插值法查找 2 public class InsertSearch { 3 public static void main(String[] args) { 4 int[] arr = new int[100]; 5 for (int i = 0; i < 100; i++) { 6 arr[i] = i+1; 7 } 8 System.out.println(Arrays.toString(arr)); 9 10 int a = insertSearch(arr,0,arr.length-1,100); 11 System.out.println(a); 12 } 13 14 public static int insertSearch(int[] arr, int left, int right, int finalVal){ 15 if(left > right || finalVal < arr[0] || finalVal > arr[arr.length-1]){ 16 return -1; 17 } 18 int mid = left + ((finalVal-arr[left])/(arr[right]-arr[left]))*(right - left); 19 int midVal = arr[mid]; 20 21 if(finalVal > midVal){ 22 return insertSearch(arr,mid+1,right,finalVal); 23 }else if(finalVal < midVal){ 24 return insertSearch(arr,left,mid-1,finalVal); 25 }else { 26 return mid; 27 } 28 } 29 }
结果
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
99