【发布时间】:2017-05-29 10:39:53
【问题描述】:
#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 或更多时,代码就会以某种方式泄漏,我无法弄清楚。我是编程新手,因此遇到了一些困难。
感谢您的宝贵时间。
【问题讨论】:
-
您是否尝试使用调试器单步执行您的代码?
标签: c++ algorithm interpolation