我在C语言上尝试了这个(二分查找)算法,它的功能是在短时间内从一堆数字中找到一个数字。这是一种非常流行的技术。你也可以在谷歌上阅读它。对我来说,它不适用于 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;
}
二分搜索需要对输入集合(在您的情况下为数组)进行排序,而此处并非如此。
改变:
a[6] = {10, 21, 32, 43, 54, 35};
对此:
a[6] = {10, 21, 32, 35, 43, 54};
这是数组的排序版本。
此外,更改:
end=5
对此:
end=6,
因为end
应该等于数组的大小 - 1,所以在进入循环之前,如您在伪代码中所见。
PS:这mid=round(mid);
不是必需的,因为整数除法的结果也将是整数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句