下面,我正在尝试使用递归函数编写一个简单的二进制搜索程序。当我运行它时,它会将要搜索的数组和键作为输入,但之后编译器会突然停止。也许是因为某处的无限循环。
#include<stdio.h>
int present_flag;
int binary_search(int array[],int low,int high,int key)
{
int mid=(high + low)/2;
if(low<=high)
{
if (array[mid] == key)
{
printf("Key found at index %d \n",mid);
return 1;
}
else if (array[mid] >key)
return 0+binary_search(array,low,mid,key);
else
return 0+binary_search(array,mid+1,high,key);;
}
else return 0;
}
main()
{
int array[9],i,n,key;
printf("Enter 9 numbers in asc order \n");
for(i=0;i<9;i++)
scanf("%d",&n);
printf("Enter number to be searched\n");
scanf("%d",&key);
present_flag=binary_search(array,0,8,key);
if (present_flag==0 )
printf("Number not present in array\n");
}