Skip to content

Instantly share code, notes, and snippets.

@joonas-yoon
Last active April 6, 2020 04:22
Show Gist options
  • Save joonas-yoon/281f1c6c396f3690d8d99b7348d9be8e to your computer and use it in GitHub Desktop.
Save joonas-yoon/281f1c6c396f3690d8d99b7348d9be8e to your computer and use it in GitHub Desktop.
alternative for STL - lower_bound, upper_bound, binary_search
template<typename T>
bool binary_search(T *arr, T *end, const T& x) {
return *lower_bound(arr, end, x) == x;
}
template<typename T>
bool binary_search(T *arr, T *end, const T& key) {
int l = 0, r = (int)(end - arr) - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (arr[mid] < key) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
return arr[l] == key;
}
template<typename T>
T* lower_bound(T *arr, T *end, const T& key) {
int l = 0, r = (int)(end - arr) - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (arr[mid] < key) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
return arr + l;
}
template<typename T>
T* upper_bound(T *arr, T *end, const T& key) {
int l = 0, r = (int)(end - arr) - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (key < arr[mid]) {
r = mid - 1;
}
else {
l = mid + 1;
}
}
return arr + l;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment