c - 这个二进制搜索实现中的无限循环?

标签 c binary-search

谁能帮我找出这个二分搜索算法实现中的错误。我猜它正在无限循环中运行。函数定义有问题但不确定是什么。

#include <stdio.h>
#define max 5

int binarysearch(int a[],int element,int first,int last);//prototype

int main(void) 
{
    int arr[max]={1,2,3,7,8};
    int b;
    int start=0;
    scanf("%d",&b);
    int search=binarysearch(arr,b,start,max-1);
    if(search==-1)
    {
        puts("element is not there in array");
    }
    else
    {
        printf("element found at position %d",search);
    }
}

int binarysearch(int a[],int element,int first,int last)//definition
{
    int mid=(first+last)/2;
    int initial;int final;
    while(first<=last)
    {
        if(a[mid]==element)
        {
            return mid;
        }
        else if(a[mid]<element)
        {
            initial=mid+1;
            final=last;
            binarysearch(a,element,initial,final);
        }
        else if(a[mid]>element)
        {
            initial=first;
            final=mid-1;
            binarysearch(a,element,initial,final);
        }
    }
    return -1;
}

最佳答案

函数内部有一个不必要的循环:

while(first<=last)

这是一个无限循环,因为 firstlast 永远不会在循环内重新分配。您已经通过在循环体内调用 binarysearch 来使用递归。将 while 更改为 if,或者删除递归调用并分配给 firstlast 而不是 initialfinal(并相应地重新计算 mid)。

如果您决定坚持使用递归方法,还要更改对 return binarysearch(...); 的调用,否则返回值将丢失。

关于c - 这个二进制搜索实现中的无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27783187/

相关文章:

c - 在单写多读线程中交换缓冲区

c - 将 C 结构数组移位 1

python - 二分查找递归错误: maximum recursion depth exceeded in comparison

c - C语言中如何将带有终止符的字符串复制到另一个字符串中?

c - 做 `char first_word[MAX_LENGTH + 1] = "test";`时,first_word是指针还是字符串?

c - 无法使用 tcpdump 捕获 IP 广播数据包

c++ - C++ 中的二进制搜索 : Ascending + Descending Ordered Arrays

duplicates - 二进制搜索,如果数组包含重复项

javascript - 使用 while 语句进行二分查找

java - 二进制搜索不起作用 - 非数组。