Path: blob/master/waterbox/libc/functions/stdlib/bsearch.c
2 views
/* bsearch( const void *, const void *, size_t, size_t, int(*)( const void *, const void * ) )12This file is part of the Public Domain C Library (PDCLib).3Permission is granted to use, modify, and / or redistribute at will.4*/56#include <stdlib.h>78#ifndef REGTEST910void * bsearch( const void * key, const void * base, size_t nmemb, size_t size, int (*compar)( const void *, const void * ) )11{12const void * pivot;13int rc;14size_t corr;15while ( nmemb )16{17/* algorithm needs -1 correction if remaining elements are an even number. */18corr = nmemb % 2;19nmemb /= 2;20pivot = (const char *)base + (nmemb * size);21rc = compar( key, pivot );22if ( rc > 0 )23{24base = (const char *)pivot + size;25/* applying correction */26nmemb -= ( 1 - corr );27}28else if ( rc == 0 )29{30return (void *)pivot;31}32}33return NULL;34}3536#endif3738#ifdef TEST39#include "_PDCLIB_test.h"4041static int compare( const void * left, const void * right )42{43return *( (unsigned char *)left ) - *( (unsigned char *)right );44}4546int main( void )47{48TESTCASE( bsearch( "e", abcde, 4, 1, compare ) == NULL );49TESTCASE( bsearch( "e", abcde, 5, 1, compare ) == &abcde[4] );50TESTCASE( bsearch( "a", abcde + 1, 4, 1, compare ) == NULL );51TESTCASE( bsearch( "0", abcde, 1, 1, compare ) == NULL );52TESTCASE( bsearch( "a", abcde, 1, 1, compare ) == &abcde[0] );53TESTCASE( bsearch( "a", abcde, 0, 1, compare ) == NULL );54TESTCASE( bsearch( "e", abcde, 3, 2, compare ) == &abcde[4] );55TESTCASE( bsearch( "b", abcde, 3, 2, compare ) == NULL );56return TEST_RESULTS;57}5859#endif606162