#include<stdio.h>
#include<stdlib.h>
int input(int *a)
{
int n,i;
printf("enter the no of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the element:");
scanf("%d",a++);
}
return n;
}
int key_input(int *a,int key)
{
int k;
printf("enter the key value which have to be searched in the array of no's provided:");
scanf("%d",&k);
return k;
}
void binary_search(int *a,int n,int key)
{
int low=0;
int high=n-1;
int mid;
while(low<=high)
{
mid=(high+low)/2;
if(key == a[mid])
{
printf("the key:%d is found at location:%d in the array",key,mid);
if(key==a[mid+1])
{
binary_search(a+mid+1,n-mid-1,key);
}
if(key==a[mid-1])
{
binary_search(a,n-mid-1,key);
}
if(key != a[mid-1] || key != a[mid+1])
break;
}
else if(key < a[mid])
high=mid-1;
else if(key>a[mid])
low=mid+1;
}
}
int main()
{
int arr[100];
int n=input(arr);
int key=key_input(arr,n);
binary_search(arr,n,key);
return 0;
}
这是我为二进制搜索编写的代码。我想找出密钥所在的所有数组位置。例如,如果我将输入 4、4、4、4 的键设为 4。输出应该包含数组(0-3)的所有位置,但我不知道代码有什么问题,它正在无限运行。有人请帮助我。