Skip to content

Instantly share code, notes, and snippets.

@Lazin
Created November 19, 2015 20:47
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 Lazin/1add7bca3c78c06ad7b2 to your computer and use it in GitHub Desktop.
Save Lazin/1add7bca3c78c06ad7b2 to your computer and use it in GitHub Desktop.
/* log_2 ceiling */
ALWAYS_INLINE unsigned lb (unsigned long x)
{
if (x <= 1) return 0;
return (8*sizeof(unsigned long))-__builtin_clzl(x-1);
}
ALWAYS_INLINE size_t
binary_search (unsigned key, unsigned * vector, size_t size)
{
unsigned * low = vector;
for (unsigned i = lb(size); i != 0; i--) {
size /= 2;
unsigned mid = low[size];
if (mid <= key)
low += size;
}
return (*low > key)? -1: low - vector;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment