Created
October 23, 2012 16:17
-
-
Save guipn/3939805 to your computer and use it in GitHub Desktop.
Generic binary search in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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