数据均匀用插值,不均匀用二分,否则和线性查找差不多
public class InterpolationSearch { public static void main(String[] args) { int[] arr = {0,1,2,3,4,5,6,7,8,9,1000000000}; int index = binarySearch(arr, 0, arr.length - 1, 6);//调用3次 // int index = interPolationSearch(arr, 0, arr.length - 1, 6);//调用7次 System.out.println(index); } //插值查找 public static int interPolationSearch(int[] arr, int left, int right, int findValue) { System.out.println("调用插值查找~~"); //防止越界 if(left > right || findValue < arr[left] || findValue > arr[right]) { return -1; } //由于取整的关系, a*b/c 不等于 a/c*b int mid = left + (right - left) * (findValue - arr[left]) / (arr[right] - arr[left]); int midVal = arr[mid]; if(findValue > midVal) { return interPolationSearch(arr, mid + 1, right, findValue); }else if(findValue < midVal) { return interPolationSearch(arr, left, mid - 1, findValue); }else { return mid; } } //二分查找 public static int binarySearch(int[] arr, int left, int right, int findVal) { System.out.println("调用二分查找~~"); if(left > right) { return -1; } int mid = (left + right) / 2; int midVal = arr[mid]; if(findVal > midVal) { return binarySearch(arr, mid + 1, right, findVal); }else if(findVal < midVal) { return binarySearch(arr, left, mid - 1, findVal); }else { return mid; } } }