【发布时间】: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