Skip to content

Instantly share code, notes, and snippets.

@djg djg/bsearch
Created Apr 27, 2010

Embed
What would you like to do?
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
You can’t perform that action at this time.