【问题标题】:Can't figure out where Binary Search algorithm went wrong无法弄清楚二分搜索算法出错的地方
【发布时间】:2018-06-19 20:26:36
【问题描述】:

我在C语言上试过这个(二分查找)算法,它的功能是在短时间内从一堆数字中找到一个数字。这是一种非常流行的技术。您也可以在 Google 上阅读有关它的信息。对我来说,它不适用于 54 和 35,即最后两个数组。每当我想搜索这两个数字时,它都会显示“找不到项目”。对于其余的数字,即数组的前 4 个数字,它工作正常。

#include <stdio.h>
#include <math.h>
int main(void)
{
    int item,beg=0,end=6,mid,a[6]={10,21,32,43,54,35};
    mid=(beg+end)/2;
    mid=round(mid);
    printf("Enter the number you want to search: ");
    scanf("%d", &item);
    printf("Item you entered is %d\n",item);
    while((a[mid]!=item) & (beg<=end))
    {
        if (item<a[mid])
            end=mid-1;
        else
            beg=mid+1;
        mid=(beg+end)/2;
        mid=round(mid);
    }

    if (item==a[mid])
        printf("Your number is at location %d in array and the number is %d",mid,a[mid]);
    else
        printf("Item not found");
    return 0;
}

【问题讨论】:

  • 请了解如何格式化您的代码以使其可读。缩进、空格和空行对编译器来说可能无关紧要,但对于试图阅读和理解代码的人来说却很重要。
  • 此外,您“尝试过这个算法”,但的算法是什么?该计划的目的是什么?你给它的输入是什么?预期和实际输出是多少?请read about how to ask good questions,也请this question checklist。并编辑您的问题以改进它,并实际提出一个问题。
  • 最后,二分搜索要求您搜索的集合是排序的
  • 另外,你为什么要四舍五入一个int? mid 在这里始终是一个 int,所以 (beg+end)/2 的结果将被截断为整数。
  • 结尾不应该是5开头吗?当您搜索 99 时,您最终会访问 a[6],这是越界的。

标签: c algorithm runtime-error binary-search


【解决方案1】:

二分搜索需要对输入集合(在您的情况下为数组)进行排序,但此处并非如此。

变化:

a[6] = {10, 21, 32, 43, 54, 35};

到这里:

a[6] = {10, 21, 32, 35, 43, 54};

这是您的数组的排序版本。

另外,改变:

end=5

到这里:

end=6,

因为end 应该等于数组的大小 - 1,所以在您进入循环之前,您可以在 pseudocode 中看到。


PS:这个mid=round(mid); 不需要,因为整数除法的结果也是整数。

【讨论】:

  • @GoswinvonBrederlow 现在都应该使用已排序的数组。
  • 是的,如果排序不好,它会检查 43,然后检查 35,然后崩溃。它不会回落到 54。这是 35 出现故障的后续影响。
  • 现在完美运行。感谢负载@GoswinvonBrederlow
  • @GoswinvonBrederlow 你是对的,我检查了算法,似乎end 应该等于 5,而不是 6!欢迎使用 9181286,欢迎使用 Stack Overflow!
  • @user9181286 有什么理由不接受我的回答吗?
猜你喜欢
  • 1970-01-01
  • 2016-12-21
  • 2015-10-26
  • 2014-09-03
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多