纯C语言:折半查找源码分享

时间:2021-05-19

复制代码 代码如下:
#include <stdio.h>
int bin_search(int key[],int low, int high,int k)
{
int mid;
if(low>high)
{
return -1;
}
else
{
mid = (low+high) / 2;
if(key[mid]==k)
return mid;
if(k>key[mid])
return bin_search(key,mid+1,high,k);
else
return bin_search(key,low,mid-1,k);
}
}

int main()
{
int n , i , addr;
int A[10] = {2,3,5,7,8,10,12,15,19,21};
printf("The contents of the Array A[10] are\n");
for(i=0;i<10;i++)
printf("%d ",A[i]);
printf("\nPlease input a interger for search\n");
scanf("%d",&n);
addr = bin_search(A,0,9,n);
if(-1 != addr)
{
printf("%d is at the %dth unit is array A\n ",n,addr);
}
else
{
printf("There is no %d in array A\n",n);
}
getchar();
return 0;
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章