c语言 - 无法找出二叉搜索算法出错的地方



我在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 %dn",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);,因为整数除法的结果也将是整数。

最新更新