您的位置:首页 > 其它

算法——二分搜索

2017-06-04 17:08 316 查看
思路:首先从数组中间的数把数组分成两部分,如果查找的数比中间的数大,说明接下来需要查找右边的部分,令中间的的下标+1为下一次开始查找的开始位置,再从low到high之间查找,一直循环。

[root@bogon code]# cat erfen.c
#include<stdio.h>
int work(int x,int a[],int len)
{
int low,mid,high;
low=0;
high=len-1;
while(low<=high)   //注意需要=号
{
mid=(low+high)/2;   //mid中间的下标
if(x>a[mid])    //查找的值比中间下标mid位置上的值大
low=mid+1;   //从mid的下一个位置开始查找,把范围缩小
else if(x<a[mid])
high=mid-1;
else
return mid;
}
return -1;   //找不到
}
int main()
{
int a[10]={1,2,3,4,5,6,7,8,9,10};
int n;
printf("please input a search num\n");
scanf("%d",&n);
int t=work(n,a,10);
if(t==-1)
printf("no this num\n");
else
printf("this num in %d\n",t);
return 0;
}
[root@bogon code]# gcc erfen.c
[root@bogon code]# ./a.out
please input a search num
7
this num in 6
[root@bogon code]#


4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: