【问题标题】:PSet 3 - CS50 - Binary Search ImplementationPSet 3 - CS50 - 二进制搜索实现
【发布时间】:2020-03-10 22:30:45
【问题描述】:

这是 edX.org 上 CS50 课程的 PSET 3。

我已经为这个问题苦苦挣扎了很长时间;特别是,我无法让 binarySearch 函数工作。我不断收到分段错误,我不知道如何处理它。我花了很多时间思考这个问题,但我没有看到它。

这是我的代码。有人可以从概念上指出我在这里歪斜的地方吗?谢谢。

#include <stdio.h>
#include <cs50.h>

bool binarySearch(int value, int values[], int min, int max)
{
    bool answer = false; 

    if (max < min)
    {
        answer = false;
    }

    else if (values[max] == value)
    {
        answer = true;
    }

    else if (values[min] == value)
    {
        answer = true;
    }

    else
    {
        int midPoint = (max + min) / 2;

        if (values[midPoint] == value)
        {
            answer = true; 
        }

        else if (values[midPoint] > value)
        {
            answer = binarySearch(value, values, min, midPoint);
        }

        else
        {
            answer = binarySearch(value, values, midPoint, max);
        }
     }

    return answer;
}

int main (int argc, char *argv[])
{
    int value = 34;

    int values[] = {11,22,33,44,55,66,77,88,99,1010};

    int max = sizeof(values) / sizeof(int);

    if (binarySearch(value, values, 0, max - 1))
    {
        printf("Found needle!\n");
    }

    else
    {
        printf("Did not find needle\n");
    }
}

当我要搜索的值不在数组中时,我不断收到分段错误。

【问题讨论】:

  • 已经很晚了,我的大脑正在关闭。在查看您的代码时,“int max = sizeof(values) / sizeof(int);”这一行可能存在问题您可能希望 'printf("max[%d]\n", max);'并验证它是否打印出您期望的内容(即:10 ?)。
  • 为什么不使用while 的简单迭代?它比递归更简单、更快、更安全……
  • @Mahonri - 我之前确实这样测试过;它提出了正确的最大尺寸。
  • @CiaPan,我无法概念化 while 循环的编码方式......

标签: c cs50


【解决方案1】:

我认为您应该将代码更改为:

 else
    {   
        int midPoint = (max + min) / 2;

        if (values[midPoint] == value)
        {
            answer = true; 
        }

        else if (values[midPoint] > value)
        {
            answer = binarySearch(value, values, min, midPoint-1); // not midPoint
        }

        else
        {
            answer = binarySearch(value, values, midPoint+1, max); //not midPoint
        }
     } 

【讨论】:

  • 这成功了!你不会相信我在这件事上花了多长时间。不过一路上我学到了很多。但是,您能否向我解释一下为什么需要添加 midPoint - 1 和 midPoint + 1。我尝试在纸上追踪这一点,但对我来说没有意义。
  • @user3237895 在唯一值为3 的单项数组中搜索7 时,尝试用一张纸和一支铅笔跟随您的程序。
【解决方案2】:

问题来了

if (max < min)

最终,max 将等于 min,但代码中的任何内容都不会强制 max 小于 min。因此,如果指定的值不在数组中,函数将永远递归。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多