C + + provides a class of STL functions to retrieve elements in an array, which is simpler and more widely used are binary_search,upper_bound and Lower_bound, which are included in the header file #include<algorithm >, use the following:
Stl
Lower_bound and Upper_bound
#include <iostream>
#include <algorithm>//the header file containing the two bounds functions
#include <cstdio>
using namespace Std;
int a[]={0,4,4,11,30,69,70,96,100},n=8,m,x,y,z,w;
void Find_lower_bound (int aim)
{
int x=1,y=n,m;
while (X<y)
{
int m=x+ (Y-X)/2;
if (A[m]>=aim) y=m;
else x=m+1;
}
printf ("\nlower_bound:%d", x);//Because the last x=y, so the output x and output y are the same
}
void Find_upper_bound (int aim)
{
int x=1,y=n,m;
while (X<y)
{
int m=x+ (Y-X)/2;
if (A[m]<=aim) x=m+1;
else y=m;
}
printf ("\nupper_bound:%d", x);//Ibid.
}
int main ()
{
Std::ios::sync_with_stdio (false);//This sentence is used to speed up CIN and cout, but after use cin,cout can not be mixed with scanf,printf, so use caution
cin>>n;
for (int i=1;i<=n;i++) scanf ("%d", &a[i]);
Sort (a+1,a+n+1);
cin>>m;
X=lower_bound (a,a+n,3)-a;//to pay attention to the wording
Y=upper_bound (a,a+n,4)-A;
Z=binary_search (a,a+n,11);//Determine whether there is a return truth
W=binary_search (a,a+n,3);//return False value if not present
printf ("%d%d%d", x,y,z,w);
Find_lower_bound (3);//function prototype
Find_upper_bound (4);//function prototype
return 0;
}
The function prototype here is actually a binary algorithm, note that the difference between the two functions is when the a[m]=aim is to shorten the interval forward or backward, which is related to the last X value.
C + + STL boundary function