/* Binary Find General edition BS (); Low_bs (), upper bound up_bs (); */#include <cstdio> #include <algorithm>using namespace Std;//[l,r int BS (int *t,int l,int R,int v) {int M;while (l<r) {m = L + (r-l)/2;//note >>1 to parentheses if (t[m] = = v) return m;if (t[m ] < v) L = m+1;else r = m;} Return-1;//-1 indicates that}//is not found for the first subscript with a value of V l//represents the interval [l,r] int low_bs (int *t,int l,int r,int) {int M;while (l<r) {m) from [L,r] looking for the Nether = L + (r-l)/2;if (T[m] >= v) r = M;elsel = m+1; } return L;} Returns a subscript r int up_bs (int *t,int l,int R,int v) {int M;while (l<r) {m = L + (r-l)/2) after the last element of V, if (T[m] <= v) {L = m + 1; }else{r = m;}}} int A[100];int Main () {int n;scanf ("%d", &n), for (int i=0;i<n;i++) scanf ("%d", &a[i]), int v;scanf ("%d", &v ); sort (a,a+n); DONT forget!! printf ("Somewhere in this element is%d\n", BS (A,0,N,V));p rintf ("The element is in a range of [%d,%d]", Low_bs (A,0,n,v), Up_bs (a,0,n,v)-1);//STLSCANF ("%d" , &n); for (int i=0;i<n;i++) scanf ("%d", &a[i]); sort (a,a+n); scanf ("%d", &v);p rintf ("lower_bound =%d\nupper_bound =%d\n", Lower_bound (A,A+N,V)-A,upper_bound (A,A+N,V)-a); return 0;}
Reference Rujia < Getting Started classic >
A probe into binary search