xref: /csrg-svn/lib/libc/stdlib/bsearch.c (revision 39300)
1*39300Sbostic /*
2*39300Sbostic  * Copyright (c) 1989 The Regents of the University of California.
3*39300Sbostic  * All rights reserved.
4*39300Sbostic  *
5*39300Sbostic  * Redistribution and use in source and binary forms are permitted
6*39300Sbostic  * provided that the above copyright notice and this paragraph are
7*39300Sbostic  * duplicated in all such forms and that any documentation,
8*39300Sbostic  * advertising materials, and other materials related to such
9*39300Sbostic  * distribution and use acknowledge that the software was developed
10*39300Sbostic  * by the University of California, Berkeley.  The name of the
11*39300Sbostic  * University may not be used to endorse or promote products derived
12*39300Sbostic  * from this software without specific prior written permission.
13*39300Sbostic  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14*39300Sbostic  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15*39300Sbostic  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16*39300Sbostic  */
17*39300Sbostic 
18*39300Sbostic #if defined(LIBC_SCCS) && !defined(lint)
19*39300Sbostic static char sccsid[] = "@(#)bsearch.c	5.1 (Berkeley) 10/14/89";
20*39300Sbostic #endif /* LIBC_SCCS and not lint */
21*39300Sbostic 
22*39300Sbostic #include <sys/types.h>
23*39300Sbostic #include <stdio.h>
24*39300Sbostic 
25*39300Sbostic char *
26*39300Sbostic bsearch(key, base, nmemb, size, compar)
27*39300Sbostic 	register char *key, *base;
28*39300Sbostic 	size_t nmemb;
29*39300Sbostic 	register size_t size;
30*39300Sbostic 	register int (*compar)();
31*39300Sbostic {
32*39300Sbostic 	register int bottom, middle, result, top;
33*39300Sbostic 	register char *p;
34*39300Sbostic 
35*39300Sbostic 	for (bottom = 0, top = nmemb - 1; bottom <= top;) {
36*39300Sbostic 		middle = (bottom + top) >> 1;
37*39300Sbostic 		p = base + middle * size;
38*39300Sbostic 		if (!(result = (*compar)(key, p)))
39*39300Sbostic 			return(p);
40*39300Sbostic 		if (result > 0)
41*39300Sbostic 			bottom = middle + 1;
42*39300Sbostic 		else
43*39300Sbostic 			top = middle - 1;
44*39300Sbostic 	}
45*39300Sbostic 	return(NULL);
46*39300Sbostic }
47