插值搜索算法是一种高效的搜索算法,它是在有序数组中查找特定元素的位置的一种改进算法。与二分搜索算法相比,插值搜索算法根据搜索值在数组中的分布情况,动态地选择搜索范围,从而更快地找到目标元素。
插值搜索算法的基本思想是通过将搜索值与数组中的元素进行比较,来确定搜索范围。它使用线性插值的方法来估计目标元素在数组中的位置,然后根据估计的位置来更新搜索范围。具体来说,算法会计算出一个插值索引,然后与目标元素进行比较,如果相等,则返回该索引;如果目标元素较小,则在插值索引的左侧继续搜索;如果目标元素较大,则在插值索引的右侧继续搜索。
- public class InterpolationSearch {
- public static int interpolationSearch(int[] arr, int target) {
- int low = 0;
- int high = arr.length - 1;
-
- while (low <= high && target >= arr[low] && target <= arr[high]) {
- if (low == high) {
- if (arr[low] == target) {
- return low;
- }
- return -1;
- }
-
- int pos = low + ((target - arr[low]) * (high - low)) / (arr[high] - arr[low]);
-
- if (arr[pos] == target) {
- return pos;
- }
-
- if (arr[pos] < target) {
- low = pos + 1;
- } else {
- high = pos - 1;
- }
- }
-
- return -1;
- }
-
- public static void main(String[] args) {
- int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
- int target = 12;
- int index = interpolationSearch(arr, target);
- if (index != -1) {
- System.out.println("元素 " + target + " 在数组中的位置为:" + index);
- } else {
- System.out.println("元素 " + target + " 不在数组中");
- }
- }
- }