二分法细节

 

总结:1.本题目中的upper_bound函数中的L=m+1;语句使得(如果V存在于数组中)最后返回值的比v所在坐标值大1(体现v出现的最大位置);

2.本题目的lower_bound函数是确定v在数组中出现的最小位置(如果存在的话);

3.本题目中v如果在数组中有多个则在区间[lower_bound,upper_bound)(左闭右开)

4.如果不能在该值的话:则upper_bound等于lower_bound,区间为空;

5.upper_boundlower_bound函数本身就是c++的库函数。

 

 1 #include<stdio.h>
 2 
 3 int num[]={3,5,7,9,10,10,10,12,15,20,25,30};//10个数
 4 
 5 int lower_bound(int *A,int L,int R,int V)
 6 
 7 {
 8 
 9     int m;
10 
11     while(L<R)
12 
13     {
14 
15         m=L+(R-L)/2;
16 
17         if(A[m]>=V) R=m;//所求点在中点以左
18 
19         else L=m+1;//所求点在中点以右
20 
21     }
22 
23     return L;
24 
25 }
26 
27 int upper_bound(int *A,int L,int R,int V)
28 
29 {
30 
31     int m;
32 
33     while(L<R)
34 
35     {
36 
37      m=L+(R-L)/2;
38 
39      if(A[m]<=V) L=m+1;//在中点以右
40 
41      else R=m;//在中点以左
42 
43     }
44 
45     return L;
46 
47 }
48 
49 int main()
50 
51 {
52 
53     int num1;
54 
55     int n=10;
56 
57     while(n--)
58 
59     {
60 
61       scanf("%d",&num1);
62 
63       int l=lower_bound(num,0,11,num1);
64 
65       int r=upper_bound(num,0,11,num1);
66 
67       if(num[l]==num1&&num[r]==num1)  printf("yes\n");
68 
69       else printf("%d  %d\n",num[l],num[r]);
70 
71     }
72 
73     return 0;
74 
75 }

 

 

 

posted @ 2014-07-18 09:01  future_hero  阅读(300)  评论(0编辑  收藏  举报