Binary search variants
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
| bool contains(const T& value) | |
| { | |
| #if 0 // variant 0 | |
| return std::binary_search(values.begin(), values.end(), value); | |
| #elif 0 // variant 1 | |
| size_t l = 0, r = values.size(); | |
| while (l < r) { | |
| size_t x = (l + r) >> 1; | |
| if (values[x] < value) | |
| l = x + 1; | |
| else if (values[x] > value) | |
| r = x; | |
| else | |
| return true; | |
| } | |
| return false; | |
| #else // variant 2 | |
| const T* base = &values[0]; // grr ignore values.size() == 0 case here. | |
| size_t n = values.size(); | |
| while (n) { | |
| size_t x = n >> 1; | |
| if (base[x] < value) { | |
| base += x + 1; | |
| n -= x + 1; | |
| } else if (base[x] > value) | |
| n = x; | |
| else | |
| return true; | |
| } | |
| return false; | |
| #endif | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment