scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | README | LICENSE

commit 649b1f8cf5bfe6ad18363c09c524fcc91d9a869a
parent 2d7e2de4bc36041ce62ca73cb4b11295a2271eae
Author: Roberto E. Vargas Caballero <k0ga@shike2.com>
Date:   Wed,  6 Dec 2017 22:54:06 +0100

[lib/c] Add bsearch()

Diffstat:
Mlib/c/src/Makefile | 1+
Alib/c/src/bsearch.c | 27+++++++++++++++++++++++++++
2 files changed, 28 insertions(+), 0 deletions(-)

diff --git a/lib/c/src/Makefile b/lib/c/src/Makefile @@ -9,6 +9,7 @@ OBJ = assert.o strcpy.o strcmp.o strlen.o strchr.o \ isalnum.o isalpha.o isascii.o isblank.o iscntrl.o isdigit.o \ isgraph.o islower.o isprint.o ispunct.o isspace.o isupper.o \ isxdigit.o toupper.o tolower.o ctype.o setlocale.o \ + bsearch.o \ printf.o fprintf.o vfprintf.o \ fgets.o gets.of fgetc.o fputc.o getchar.o putchar.o \ fputs.o puts.o fread.o fwrite.o \ diff --git a/lib/c/src/bsearch.c b/lib/c/src/bsearch.c @@ -0,0 +1,27 @@ + +#include <stdlib.h> + +void * +bsearch(const void *key, const void *ary, size_t n, size_t size, + int (*cmp)(const void *, const void *)) +{ + int t; + size_t mid, low, high; + const char *cur, *base = ary; + + low = 0; + high = n - 1; + while (low <= high) { + mid = low + (high - low) / 2; + cur = base + mid*size; + + if ((t == (*cmp)(key, cur)) == 0) + return (void *) cur; + else if (t > 0) + low = mid + 1; + else + high = mid - 1; + } + + return NULL; +}