Skip to content

Instantly share code, notes, and snippets.

@imoasislee
Created February 24, 2022 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imoasislee/48b428aa128f6cc4aa08c45b9d0bfe06 to your computer and use it in GitHub Desktop.
Save imoasislee/48b428aa128f6cc4aa08c45b9d0bfe06 to your computer and use it in GitHub Desktop.
// binary_search
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
struct Rule
{
bool operator() (const int & a1, const int & a2) const {
return a1%10 < a2%10; // 按个位数从小到大排序
}
};
void Print(int a[], int size)
{
for (int i=0; i<size; ++i)
{
cout << a[i] << ",";
}
cout << endl;
}
int main()
{
int a[] = {12,45,3,98,21,7};
sort(a,a+6);
Print(a,6);
cout<<"result:"<<binary_search(a,a+6,12)<<endl; // 可以查找到,返回1
cout<<"result:"<<binary_search(a,a+6,77)<<endl; // 无法查找到,返回0
sort(a,a+6,Rule());
Print(a,6);
cout<<"result:"<<binary_search(a,a+4,7,Rule())<<endl; // 不包含下标为4的元素,返回0
cout<<"result:"<<binary_search(a,a+5,7,Rule())<<endl; // 包含下标为4的元素,返回1
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment