Skip to content

Instantly share code, notes, and snippets.

@oskimura
Created July 16, 2020 10:06
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 oskimura/bc0b5cd6a37847890df7d4054b9e350d to your computer and use it in GitHub Desktop.
Save oskimura/bc0b5cd6a37847890df7d4054b9e350d to your computer and use it in GitHub Desktop.
template<class T>
bool isOK(vector<T> a, int index, T key)
{
// ここの比較でupper boundかlower bound か決まる
if (a[index] > key) {
return true;
}
else {
return false;
}
}
template<class T>
T binarysearch(vector<T> a, T key)
{
int left = -1;
int right = (int) a.size();
while (abs(right - left) > 1) {
int mid = left + (right - left) / 2;
/*
cout << "left " << left << endl;
cout << "right " << right << endl;
cout << "mid " << mid << endl;
*/
if (isOK(a, mid,key)) {
right = mid;
}
else {
left = mid;
}
}
//cout << "return " << right << endl;
return right;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment