#include <iostream>
#include <string>
using namespace std;
int main()
{
int arr[] = {1,3,5,7,9,11,13,15,17,19,21};
int first, last, pos, key;
first = 0;
last = (sizeof(arr)/ sizeof(arr[0])) - 1;
cout << "Enter the key value:\t" << endl;
cin >> key;
//The search code starts from here
while(first <= last && key >= first && key <= last) {
pos = first + (((last - first)/(arr[last] - arr[first])) * (key - arr[first]));
if(key < arr[pos]) {
last = pos - 1;
}
else if(key > arr[pos]) {
first = pos + 1;
}
else {
cout << "Found the value at index:\t" << pos << endl;
break;
}
}
//if the value is not found
if(first > last) {
cout << "The value is not found." << endl;
}
return 0;
}
該算法的工作原理從零到10.但是,無論何時輸入11或更多,代碼都會以某種方式泄漏,這是我無法弄清楚的。我是編程新手,因此我面臨一些困難。爲什麼此插值搜索算法僅適用於1位數值? (不適用於大於10的密鑰)
謝謝你的時間。
你嘗試通過** **使用調試你的代碼一步? –