求C语言折半查找法 代码
拿15个静态常量做的测试
#include<stdio.h>
//要先写 第一个元素的值为0的排除子函数,没写。
int arrange(int x,int a[],int low,int high)
{
int flag=0;
int mid =(low+high)/2;
if((high-low)==0 || (high - low) == 1) //二分法排序的最后两种可能
{
if(a[mid]==x)
return x;
else
return 0;
}
int left;
int right;
left=arrange(x,a,low,mid); //向左
right=arrange(x,a,mid,high); //向右
if(left||right) //整合,有一个非0就是找到值了
return a[left+right];
else
return 0;
}
int main()
{
int a[]={-8,-5,-2,-1,2,5,8,10,18,21,23,7,9,1,13};
int result,x;
printf(" {12,14,15,16,2,5,8,10,18,21,23,7,9,1,13} \n");
printf("input the number you want:");
scanf("%d",&x);
result=arrange(x,a,1,15);
if( result != 0)
printf("%d\n",result);
else
printf("there is no number!\n");
return 0;
}
-
上一篇:用c#实现折半查找
-
下一篇:求C语言编写程序折半查找程序