Skip to content

Instantly share code, notes, and snippets.

@djg
Created April 27, 2010 07:14
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 djg/380449 to your computer and use it in GitHub Desktop.
Save djg/380449 to your computer and use it in GitHub Desktop.
int* bsearch(int val, int* base, int nelems)
{
if (base == NULL || nelems == 0)
return NULL;
int lo = 0;
int hi = nelems - 1;
for (;;)
{
int m = (lo + hi + 1) / 2;
if (base[m] == val)
return base + m;
else if (lo == hi)
return NULL;
else if (base[m] < val)
lo = m;
else if (base[m] > val)
hi = m;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment