Java 版插值算法
程序员文章站
2022-05-18 07:56:01
...
插值算法
package com.wmq.demo01.search;
/**
* 插值查找
*/
public class InsertValSearch {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7,8,9,10};
/*for (int i = 0; i < 100; i++) {
arr[i] = i + 1;
}*/
int index = search(arr, 0, arr.length - 1, 1);
System.out.println(index);
}
public static int search(int[] arr,int left,int right,int findVal){
if (left > right || findVal < arr[0] || findVal > arr[arr.length - 1]) {
return -1;
}
// 求出mid, 自适应
int mid = left + (right - left) * (findVal - arr[left]) / (arr[right] - arr[left]);
int midVal = arr[mid];
if (findVal > midVal) { // 说明应该向右边递归
return search(arr, mid + 1, right, findVal);
} else if (findVal < midVal) { // 说明向左递归查找
return search(arr, left, mid - 1, findVal);
} else {
return mid;
}
}
}