add SDL_bsearch

This commit is contained in:
Ozkan Sezer 2022-04-25 23:55:50 +03:00 committed by Ozkan Sezer
parent 0b2a55ea7d
commit e9ff4fdd49
17 changed files with 52 additions and 6 deletions

View file

@ -534,5 +534,38 @@ extern void qsortG(void *base, size_t nmemb, size_t size,
#endif /* HAVE_QSORT */
void *
SDL_bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compare)(const void *, const void *))
{
#if defined(HAVE_BSEARCH)
return bsearch(key, base, nmemb, size, compare);
#else
/* SDL's replacement: Taken from the Public Domain C Library (PDCLib):
Permission is granted to use, modify, and / or redistribute at will.
*/
const void *pivot;
size_t corr;
int rc;
while (nmemb) {
/* algorithm needs -1 correction if remaining elements are an even number. */
corr = nmemb % 2;
nmemb /= 2;
pivot = (const char *)base + (nmemb * size);
rc = compare(key, pivot);
if (rc > 0) {
base = (const char *)pivot + size;
/* applying correction */
nmemb -= (1 - corr);
} else if (rc == 0) {
return (void *)pivot;
}
}
return NULL;
#endif /* HAVE_BSEARCH */
}
/* vi: set ts=4 sw=4 expandtab: */