1 #include <stdio.h>
2 #include<stdlib.h>
3
4 int binsearch(int x,int v[],int n);//函数声明
5
6 int main()
7 {
8 int arr[]={1,2,3,4,5,6,7,8,9,10};
9 int 结果,num;
10 num=7;
11 结果=binsearch(num,arr,10);
12
13 if(结果<0)
14 printf("没找到!
");
15 else
16 printf("在arr[%d]找到%d
",结果,num);
17 system("pause");
18
19 return 0;
20 }
21
22 int binsearch(int x,int v[],int n)//函数定义
23 {
24 int low,high,mid;//最小,最大,中间
25
26 low=0;
27 high=n-1;
28
29 while(low<=high){//不停折半
30
31 mid=(low+high)/2;
32 if(x<v[mid]) //如果要找的数比中间的小
33 high=mid-1;//扔掉一半
34 else if(x>v[mid])//如果比中间的大
35 low=mid+1;//扔掉另一半
36 else
37 return mid;//找到
38
39
40 }
41
42 return -1;//没找到
43 }