无法弄清楚二进制搜索算法哪里出错了
Can't figure out where Binary Search algorithm went wrong
我在C语言上试过这个(二分查找)算法,它的作用是在很短的时间内从一堆数中找出一个数。这是一种非常流行的技术。您也可以在 Google 上阅读相关内容。对我来说,它不适用于 54 和 35,即数组的最后两个数字。每当我想搜索这两个数字时,它都会显示 "Item not found"。对于其余数字,即数组的前 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,在你进入循环之前,正如你在 pseudocode.
中看到的
PS:不需要这个mid=round(mid);
,因为整数除法的结果也是整数。
我在C语言上试过这个(二分查找)算法,它的作用是在很短的时间内从一堆数中找出一个数。这是一种非常流行的技术。您也可以在 Google 上阅读相关内容。对我来说,它不适用于 54 和 35,即数组的最后两个数字。每当我想搜索这两个数字时,它都会显示 "Item not found"。对于其余数字,即数组的前 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,在你进入循环之前,正如你在 pseudocode.
PS:不需要这个mid=round(mid);
,因为整数除法的结果也是整数。