#include <stdio.h>
void search(int a[],int n,int k)
{
int i=n;
a[0]=k;
while(a[i]!=k)
i--;
if(i==0)
printf("查找失败!\n");
else
printf("数据是数组中的第%d个数\n",i);
}
void binary_search(int a[],int n,int k)
{
int low,mid,high;
int time=0;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
time=time+1;
if(a[mid]==k)
{
printf("数据是数组中的第%d个数\n",mid);
printf("查找次数为%d次\n",time);
break;
}
else if(a[mid]<k)
low=mid+1;
else
high=mid-1;
}
}
void main()
{
int a[100];
int i,key,n;
printf("the length of number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("输入要查找的数据:");
scanf("%d",&key);
binary_search(a,n,key);
search(a,n,key);
}
C语言实现查找算法
最新推荐文章于 2024-09-10 20:37:53 发布