package com.atguigu.search;
import java.util.Arrays;
public class InsertValueSearch {
public static void main(String[] args) {
int arr[] = { 1, 8, 10, 89,1000,1000, 1234 };
int index = insertValueSearch(arr, 0, arr.length - 1, 1234);
System.out.println("index = " + index);
}
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;
}
}
public static int insertValueSearch(int[] arr, int left, int right, int findVal) {
System.out.println("插值查找次数~~");
if (left > right || findVal < arr[0] || findVal > arr[arr.length - 1]) {
return -1;
}
int mid = left + (right - left) * (findVal - arr[left]) / (arr[right] - arr[left]);
int midVal = arr[mid];
if (findVal > midVal) {
return insertValueSearch(arr, mid + 1, right, findVal);
} else if (findVal < midVal) {
return insertValueSearch(arr, left, mid - 1, findVal);
} else {
return mid;
}
}
}
差值查找注意事项
- 对于数据量较大,关键字分布比较均匀的查找表来书,采用差值查找,速度较快,
- 关键字分布不均匀的情况下,该方法不一定比折半查找要好