无法弄清楚二进制搜索算法哪里出错了

标签 c algorithm runtime-error binary-search

我在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;
}

最佳答案

二分搜索要求输入集合(在您的例子中是数组)被排序,这里不是这种情况。

改变:

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); 不是必需的,因为整数除法的结果也将是整数。

关于无法弄清楚二进制搜索算法哪里出错了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50928029/

相关文章:

c - 如何读取数组中int的随机数

multithreading - 为什么比较和交换 (CAS) 算法是无锁同步的好选择?

c++ - 表达式 : _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) Error

python - 调用 hub.text_embedding_column 方法时如何修复 "RuntimeError: Missing implementation that supports: loader"?

python - 从 pd.DataFrame 设置 dtypes 给出 TypeError : object of type 'type' has no len()

c - read() 和 write() 使用 spi 设备驱动程序

C、struct的第一个成员

c - 在使用 fork() 创建的 C 中,将值从子进程返回到其父进程

c++ - Bag of Features 如何运作?

algorithm - 理解寻找最小圆包围点的算法