Last active
April 6, 2020 04:22
-
-
Save joonas-yoon/281f1c6c396f3690d8d99b7348d9be8e to your computer and use it in GitHub Desktop.
alternative for STL - lower_bound, upper_bound, binary_search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<typename T> | |
bool binary_search(T *arr, T *end, const T& x) { | |
return *lower_bound(arr, end, x) == x; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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