about summary refs log tree commit diff
path: root/src/stdlib/bsearch.c
blob: 61d89367e7b9140fa7dc067558427dc2aeed223c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdlib.h>

void *bsearch(const void *key, const void *base, size_t nel, size_t width, int (*cmp)(const void *, const void *))
{
	void *try;
	int sign;
	while (nel > 0) {
		try = (char *)base + width*(nel/2);
		sign = cmp(key, try);
		if (!sign) return try;
		else if (nel == 1) break;
		else if (sign < 0)
			nel /= 2;
		else {
			base = try;
			nel -= nel/2;
		}
	}
	return NULL;
}