谁能帮我找出这个二分搜索算法实现中的错误。我猜它正在无限循环中运行。函数定义有问题但不确定是什么。
#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)
这是一个无限循环,因为 first
和 last
永远不会在循环内重新分配。您已经通过在循环体内调用 binarysearch
来使用递归。将 while
更改为 if
,或者删除递归调用并分配给 first
和 last
而不是 initial
和 final
(并相应地重新计算 mid
)。
如果您决定坚持使用递归方法,还要更改对 return binarysearch(...);
的调用,否则返回值将丢失。
关于c - 这个二进制搜索实现中的无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27783187/