【问题标题】:What is the role of the (if block) inside the function in the code below?下面代码中函数内部的(if 块)的作用是什么?
【发布时间】:2017-11-04 05:17:38
【问题描述】:

这是我在 YouTube 视频中找到的插值搜索,但没有声音。我已经理解了代码中的大部分内容,但为什么我需要使用 if(key == arr[low])?

if (key == arr[low]){

    return low ;

} else {

    return -1;

}

整个程序都在下面。

#include <iostream>
#include <cmath>
using namespace std;

int z = 0;

int interpolation(int arr[], int left, int right, int key){

    int low = left;
    int high = right - 1;
    int mid;

    while (arr[high] != arr[low] && key >= arr[low] && key <= arr[high]) {

        mid = low + ( (key - arr[low]) * (high - low) / (arr[high] - arr[low]) );

        if (key > arr[mid]){

            low = mid + 1;

        } else if (key < arr[mid]){

            high = mid - 1;

        } else{

            return mid;

        }

    }

    if (key == arr[low]){

        return low ;

    } else {

        return -1;

    }

}

int main()
{

    int L[] = {0, 1, 2, 3, 4, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610};
    //int L[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    int left = 0;
    int right = sizeof(L) / sizeof(L[0]);

    int key = 6;

    int x;
    if((x = interpolation(L, left, right, key)) == -1 ){

        cout << "Key doesn't exist"<< endl;

    } else {

        cout << "The position of Key is " << x << endl;

    }

return 0; }

没有这部分,一些索引就不起作用。但是,while 循环中的 else 不是覆盖了整个事情吗?

else{

     return mid;

}

谢谢。

【问题讨论】:

  • 可以处理仅由一个元素组成的数组的情况。在这种情况下,while 主循环根本不会运行。

标签: arrays algorithm c++11 linear-interpolation


【解决方案1】:

while 循环结束时,以下一个或多个条件为真:

  1. arr[high] == arr[low],或
  2. key &lt; arr[low],或
  3. key &gt; arr[high]

这是DeMorgan's Lawswhile 的延续条件的应用。

如果只有条件 2 或 3 为真,则找不到 key,因此算法返回 -1。如果条件 1 为真,您会在 highlow 之间找到一个“平坦”延伸。在这种情况下,如果arr[low]arr[high] 匹配key,算法应该返回lowhigh 之间的任何索引;如果平面拉伸的数字与key 不匹配,则返回-1。

while 循环中的 else 不是覆盖了整个事情吗?

如果您在使用搜索键击中该位置之前发现一个平坦的拉伸段,您可能无法到达循环中的那个部分。你需要这个条件,因为当函数运行平坦时,梯度搜索是不可能的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-30
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多