二分查找(等于x,小于x,小于等于x,大于x,大于等于x )


//等于x
//小于x
//小于等于x
//大于x
//大于等于x


 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cmath>
 4 #include <cstring>
 5 #include <string>
 6 #include <set>
 7 #include <map>
 8 #include <list>
 9 #include <stack>
10 #include <queue>
11 #include <vector>
12 #include <algorithm>
13 #include <iostream>
14 using namespace std;
15 #define ll long long
16 #define minv 1e-6
17 #define inf 1e9
18 const long maxn=1e5+5;
19 const ll mod=1e9+7;
20 
21 //µÈÓÚx
22 //СÓÚx
23 //СÓÚµÈÓÚx
24 //´óÓÚx
25 //´óÓÚµÈÓÚx 
26 
27 long a[maxn];
28 
29 int main()
30 {
31     long n,s,i,l,r,m;
32     scanf("%ld",&n);
33     for (i=1;i<=n;i++)
34         scanf("%ld",&a[i]);
35     scanf("%ld",&s);
36     l=1; r=n;
37     while (l<=r)
38     {
39         m=(l+r)>>1;
40         if (a[m]>=s) //a[l]>=s
41             r=m-1; //a[r]<s
42         else
43             l=m+1;
44     }
45     printf("%ld\n",a[l]);
46     printf("%ld\n",a[r]);
47     /*
48         8 1 1 1 4 4 6 6 6
49         0
50         1 0
51         
52         8 1 1 1 4 4 6 6 6
53         10
54         0 6
55         
56         8 1 1 1 4 4 6 6 6
57         4
58         4 1
59         
60         
61         8 1 1 1 4 4 6 6 6
62         3
63         4 1
64         
65         8 1 1 1 4 4 6 6 6
66         5
67         6 4
68         
69         
70          
71          
72     */
73     return 0;
74 }

 

 


  a[l]>s a[r]<=s

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cmath>
 4 #include <cstring>
 5 #include <string>
 6 #include <set>
 7 #include <map>
 8 #include <list>
 9 #include <stack>
10 #include <queue>
11 #include <vector>
12 #include <algorithm>
13 #include <iostream>
14 using namespace std;
15 #define ll long long
16 #define minv 1e-6
17 #define inf 1e9
18 const long maxn=1e5+5;
19 const ll mod=1e9+7;
20 
21 //µÈÓÚx
22 //СÓÚx
23 //СÓÚµÈÓÚx
24 //´óÓÚx
25 //´óÓÚµÈÓÚx 
26 
27 long a[maxn];
28 
29 int main()
30 {
31     long n,s,i,l,r,m;
32     scanf("%ld",&n);
33     for (i=1;i<=n;i++)
34         scanf("%ld",&a[i]);
35     scanf("%ld",&s);
36     l=1; r=n;
37     while (l<=r)
38     {
39         m=(l+r)>>1;
40         if (a[m]>s) //a[l]>s
41             r=m-1; //a[r]<=s
42         else
43             l=m+1;
44     }
45     printf("%ld\n",a[l]);
46     printf("%ld\n",a[r]);
47     /*
48         8 1 1 1 4 4 6 6 6
49         0
50         1 0
51         
52         8 1 1 1 4 4 6 6 6
53         10
54         0 6
55         
56         8 1 1 1 4 4 6 6 6
57         4
58         6 4
59         
60         
61         8 1 1 1 4 4 6 6 6
62         3
63         4 1
64         
65         8 1 1 1 4 4 6 6 6
66         5
67         6 4
68         
69         
70          
71          
72     */
73     return 0;
74 }

 

若要判断相等,则

Code1 : if l!=n+1 && a[l]==s

Code2 : if r!=0 && a[r]==s

 

posted @ 2018-05-25 08:37  congmingyige  阅读(932)  评论(0编辑  收藏  举报