我不断收到段错误错误。递归函数调用是问题所在。但是,我无法解决它!
#include<stdio.h>
int binarysearch(int a[],int l,int x,int y){
if(x>=l)
{
int mid= 1 + (x-1)/2;
if(a[mid]==y) return mid;
if(a[mid] > y) {return binarysearch(a, l, mid-1, y);}
else{return binarysearch(a, mid+1, x, y);}
}
return -1;
}
void main()
{
int a[]={2,3,4};
int x=sizeof(a)/sizeof(a[0]);
int y=2;
int result =binarysearch(a,0,x-1,y);
(result==-1)?printf("the number is not present in the array"):
printf("the number is present at index%d",result);
}
最佳答案
在binarysearch()
中,行
int mid= 1 + (x-1)/2;
可以制作
int mid=(x+l)/2;
即,mid
将是当前正在考虑的数组部分的最低和最大索引之和除以 2
的整数。
关于c - 递归函数调用中的段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46501872/