Skip to content

Instantly share code, notes, and snippets.

@rygorous
Created February 5, 2012 21:34
Show Gist options
  • Save rygorous/1748043 to your computer and use it in GitHub Desktop.
Save rygorous/1748043 to your computer and use it in GitHub Desktop.
Binary search variants
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