java为什么插值搜索如果是手动计算的,那么它只执行2个步骤,但编程时超过2个步骤
我被插值搜索计算搞糊涂了,该程序提供了与手动计算不同的步长结果
输入数据:{3, 5, 10, 14, 21}
我想找到14号。如果手动计算,只需两步即可找到14
我在我的插值搜索程序中尝试了这个
System.out.println("post low higth " + post + " " + low + " " + hight);
它显示了找到我要找的密钥的3个步骤,如下面的picture所示
但当我这么做的时候
System.out.println("mid row col dataMid: " + mid + " " + left + " " + right);
在二进制搜索中,程序中的手动计算和循环是相同的,只有两个步骤,如下面的picture所示
谁能解释一下为什么会这样
这是我的插值搜索代码
public static void interpolationSearch(int[] arr, int key){
int low,hight,post;
low = 0;
hight = arr.length-1;
while (low<=hight){
post = low+((key-arr[low])/(arr[hight]-arr[low]))*(hight-low);
System.out.println("post low higth " + post + " " + low + " " + hight);
if (key == arr[post]){
System.out.println("Data found");
System.out.println("data ada di indeks ke-: "+post);
return ;
}
else if (arr[post]>key){
hight = post-1;
}else {
low = post+1;
}
}
}
这是我的二进制搜索代码
public static void binarySearch(int arr[], int key) {
int left = 0;
int right = arr.length - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
System.out.println("mid left hight: " + mid + " " + left + " " + right);
//divide and conquer
if(key == arr[mid]) {
System.out.println("Data ditemukan!");
return;
} else if(key > arr[mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
System.out.println("Data tidak ditemukan!");
}
共 (0) 个答案