139300Sbostic /*
2*61180Sbostic * Copyright (c) 1990, 1993
3*61180Sbostic * The Regents of the University of California. All rights reserved.
439300Sbostic *
542124Sbostic * %sccs.include.redist.c%
639300Sbostic */
739300Sbostic
839300Sbostic #if defined(LIBC_SCCS) && !defined(lint)
9*61180Sbostic static char sccsid[] = "@(#)bsearch.c 8.1 (Berkeley) 06/04/93";
1039300Sbostic #endif /* LIBC_SCCS and not lint */
1139300Sbostic
1250459Sbostic #include <stddef.h>
1342179Sbostic #include <stdlib.h>
1439300Sbostic
1542124Sbostic /*
1642124Sbostic * Perform a binary search.
1742124Sbostic *
1842124Sbostic * The code below is a bit sneaky. After a comparison fails, we
1942124Sbostic * divide the work in half by moving either left or right. If lim
2042124Sbostic * is odd, moving left simply involves halving lim: e.g., when lim
2142124Sbostic * is 5 we look at item 2, so we change lim to 2 so that we will
2242124Sbostic * look at items 0 & 1. If lim is even, the same applies. If lim
2342124Sbostic * is odd, moving right again involes halving lim, this time moving
2442124Sbostic * the base up one item past p: e.g., when lim is 5 we change base
2542124Sbostic * to item 3 and make lim 2 so that we will look at items 3 and 4.
2642124Sbostic * If lim is even, however, we have to shrink it by one before
2742124Sbostic * halving: e.g., when lim is 4, we still looked at item 2, so we
2842124Sbostic * have to make lim 3, then halve, obtaining 1, so that we will only
2942124Sbostic * look at item 3.
3042124Sbostic */
3142124Sbostic void *
bsearch(key,base0,nmemb,size,compar)3242124Sbostic bsearch(key, base0, nmemb, size, compar)
3346599Sdonn register const void *key;
3446599Sdonn const void *base0;
3539300Sbostic size_t nmemb;
3639300Sbostic register size_t size;
3746599Sdonn register int (*compar) __P((const void *, const void *));
3839300Sbostic {
3946599Sdonn register const char *base = base0;
4051742Storek register size_t lim;
4151742Storek register int cmp;
4246599Sdonn register const void *p;
4339300Sbostic
4442124Sbostic for (lim = nmemb; lim != 0; lim >>= 1) {
4542124Sbostic p = base + (lim >> 1) * size;
4642124Sbostic cmp = (*compar)(key, p);
4742124Sbostic if (cmp == 0)
4846599Sdonn return ((void *)p);
4942124Sbostic if (cmp > 0) { /* key > p: move right */
5042124Sbostic base = (char *)p + size;
5142124Sbostic lim--;
5250459Sbostic } /* else move left */
5339300Sbostic }
5442124Sbostic return (NULL);
5539300Sbostic }
56