]> pd.if.org Git - pdclib/blobdiff - functions/stdlib/bsearch.c
PDCLib includes with quotes, not <>.
[pdclib] / functions / stdlib / bsearch.c
index 7764d4763dd80217a060772211349362257c4939..835407f5ee8e2314100cee595a1e25d44346d5a3 100644 (file)
@@ -1,13 +1,7 @@
-/* $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).
    Permission is granted to use, modify, and / or redistribute at will.
-
-   Code taken from Paul Edward's PDPCLIB.
 */
 
 #include <stdlib.h>
@@ -18,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 )
         {
@@ -42,16 +37,15 @@ void * bsearch( const void * key, const void * base, size_t nmemb, size_t size,
 #endif
 
 #ifdef TEST
-#include <_PDCLIB_test.h>
+#include "_PDCLIB_test.h"
 
-int compare( const void * left, const void * right )
+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 );