|
|
1.1 ! root 1: /* ! 2: * Copyright (c) 1990 Regents of the University of California. ! 3: * All rights reserved. ! 4: * ! 5: * Redistribution and use in source and binary forms are permitted ! 6: * provided that: (1) source distributions retain this entire copyright ! 7: * notice and comment, and (2) distributions including binaries display ! 8: * the following acknowledgement: ``This product includes software ! 9: * developed by the University of California, Berkeley and its contributors'' ! 10: * in the documentation or other materials provided with the distribution ! 11: * and in all advertising materials mentioning features or use of this ! 12: * software. Neither the name of the University nor the names of its ! 13: * contributors may be used to endorse or promote products derived ! 14: * from this software without specific prior written permission. ! 15: * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR ! 16: * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED ! 17: * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ! 18: */ ! 19: ! 20: #if defined(LIBC_SCCS) && !defined(lint) ! 21: static char sccsid[] = "@(#)bsearch.c 5.3 (Berkeley) 5/17/90"; ! 22: #endif /* LIBC_SCCS and not lint */ ! 23: ! 24: #include <stddef.h> /* size_t */ ! 25: #include <stdlib.h> ! 26: ! 27: /* ! 28: * Perform a binary search. ! 29: * ! 30: * The code below is a bit sneaky. After a comparison fails, we ! 31: * divide the work in half by moving either left or right. If lim ! 32: * is odd, moving left simply involves halving lim: e.g., when lim ! 33: * is 5 we look at item 2, so we change lim to 2 so that we will ! 34: * look at items 0 & 1. If lim is even, the same applies. If lim ! 35: * is odd, moving right again involes halving lim, this time moving ! 36: * the base up one item past p: e.g., when lim is 5 we change base ! 37: * to item 3 and make lim 2 so that we will look at items 3 and 4. ! 38: * If lim is even, however, we have to shrink it by one before ! 39: * halving: e.g., when lim is 4, we still looked at item 2, so we ! 40: * have to make lim 3, then halve, obtaining 1, so that we will only ! 41: * look at item 3. ! 42: */ ! 43: void * ! 44: bsearch(key, base0, nmemb, size, compar) ! 45: register void *key; ! 46: void *base0; ! 47: size_t nmemb; ! 48: register size_t size; ! 49: register int (*compar)(); ! 50: { ! 51: register char *base = base0; ! 52: register int lim, cmp; ! 53: register void *p; ! 54: ! 55: for (lim = nmemb; lim != 0; lim >>= 1) { ! 56: p = base + (lim >> 1) * size; ! 57: cmp = (*compar)(key, p); ! 58: if (cmp == 0) ! 59: return (p); ! 60: if (cmp > 0) { /* key > p: move right */ ! 61: base = (char *)p + size; ! 62: lim--; ! 63: } /* else move left */ ! 64: } ! 65: return (NULL); ! 66: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.