Skip to content

Instantly share code, notes, and snippets.

@guipn
Created October 23, 2012 16:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guipn/3939805 to your computer and use it in GitHub Desktop.
Save guipn/3939805 to your computer and use it in GitHub Desktop.
Generic binary search in C
/*
* This differs from the standard function `bsearch` in the following important ways:
*
* 1. Parameter ordering: this version groups entities with their sizes;
* 2. Return value type: this version returns an index, or -1 if the key isn't present. This is more useful;
* 3. Speed: this version is likely slower in an implementation-defined way;
* 4. Consistence: this version has not been thoroughly tested.
*
*/
int binsearch(void *elt, size_t size, void *arr, size_t length, int (*compare)(void *, void *))
{
size_t i = length / 2;
char *array = arr;
while (i < length)
{
int comparison = compare(array + i * size, elt);
if (comparison == 0)
{
return i;
}
if (comparison < 0)
{
i += (length - i + 1) / 2;
}
else
{
length = i;
i /= 2;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment