X-Git-Url: https://pd.if.org/git/?a=blobdiff_plain;f=functions%2Fstdlib%2Fbsearch.c;h=211c55c0a82082c1cbd706cd3e6e6988678193b2;hb=d865c4403fc91d1f1ac95ba76febcee9f429bb97;hp=881c99af99e5414bd58def477d76abcd7afe2d85;hpb=fcdedc037cdd1e5137ae38892a980257fab057f7;p=pdclib diff --git a/functions/stdlib/bsearch.c b/functions/stdlib/bsearch.c index 881c99a..211c55c 100644 --- a/functions/stdlib/bsearch.c +++ b/functions/stdlib/bsearch.c @@ -1,7 +1,3 @@ -/* $Id$ */ - -/* Release $Name$ */ - /* bsearch( const void *, const void *, size_t, size_t, int(*)( const void *, const void * ) ) This file is part of the Public Domain C Library (PDCLib). @@ -16,18 +12,19 @@ void * bsearch( const void * key, const void * base, size_t nmemb, size_t size, { const void * pivot; int rc; - int corr; + size_t corr; while ( nmemb ) { /* algorithm needs -1 correction if remaining elements are an even number. */ - corr = ( nmemb % 2 ) - 1; + corr = nmemb % 2; nmemb /= 2; pivot = (const char *)base + (nmemb * size); rc = compar( key, pivot ); if ( rc > 0 ) { base = (const char *)pivot + size; - nmemb += corr; + /* applying correction */ + nmemb -= ( 1 - corr ); } else if ( rc == 0 ) { @@ -40,16 +37,16 @@ void * bsearch( const void * key, const void * base, size_t nmemb, size_t size, #endif #ifdef TEST -#include <_PDCLIB_test.h> -int compare( const void * left, const void * right ) +#include "_PDCLIB_test.h" + +static int compare( const void * left, const void * right ) { return *( (unsigned char *)left ) - *( (unsigned char *)right ); } -int main() +int main( void ) { - BEGIN_TESTS; TESTCASE( bsearch( "e", abcde, 4, 1, compare ) == NULL ); TESTCASE( bsearch( "e", abcde, 5, 1, compare ) == &abcde[4] ); TESTCASE( bsearch( "a", abcde + 1, 4, 1, compare ) == NULL );