【问题标题】:Why this Interpolation search algorithm correctly works for only 1 digit values? ( does not work with key greater than 10)为什么此插值搜索算法仅适用于 1 位数的值? (不适用于大于 10 的密钥)
【发布时间】: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


【解决方案1】:

问题在于,当您将两个整数值相除时,如果第一个值(分子)小于第二个值(分母),您将得到零。然后你需要先做乘法来增加分子的值。尝试使用此代码:

pos = first + (last - first) * (key - arr[first]) / (arr[last] - arr[first]);

或者老老实实使用浮点计算:

//The search code starts from here
while(first <= last && key >= first && key <= last) {
    pos = (int)((double)first + (double)(last - first) * (double)(key - arr[first]) / (double)(arr[last] - 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;
    }
}

【讨论】:

  • 代码 sn-ps,没有任何解释作为答案是无用的(不要向 OP 提供关于问题原因的更多知识)。
  • 谢谢。添加评论
  • 对不起,不起作用。我刚刚复制了您的代码行替换为我的代码行,但仍然存在相同的错误。此外,使用 double pos 会报错:invalid types 'double [11][double]' for array subscription.
  • 拿出一支铅笔和一张纸,用手追踪输入值 11 的代码。我做了 5 分钟...你为什么不这样做?
猜你喜欢
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 2020-03-18
  • 1970-01-01
  • 2022-10-16
  • 2023-03-31
  • 1970-01-01
  • 2013-04-10
相关资源
最近更新 更多