shithub: scc

Download patch

ref: a06125b256611ed9a97f7b1664beff5a6d27c52f
parent: 4eb0595fdcfb5064a5f81b1ffe4fb2de4c6a3dd3
author: Roberto E. Vargas Caballero <[email protected]>
date: Wed Dec 6 17:54:06 EST 2017

[lib/c] Add bsearch()

--- a/lib/c/src/Makefile
+++ b/lib/c/src/Makefile
@@ -9,6 +9,7 @@
       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 \
--- /dev/null
+++ b/lib/c/src/bsearch.c
@@ -1,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;
+}