#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;
}
此算法从0到10工作。但是,每当我输入11或更多时,代码就会以某种方式泄漏,而我无法弄清楚。我是编程新手,因此,我遇到了一些困难。
感谢您的时间。
答案 0 :(得分:0)
问题在于,当你划分两个整数值时,如果第一个值(分子)小于第二个(分母),你就会得到零。然后你需要先通过乘法来增加分子的值。尝试使用此代码:
onChange
或者诚实地使用浮点计算:
pos = first + (last - first) * (key - arr[first]) / (arr[last] - arr[first]);