1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License, Version 1.0 only 6 * (the "License"). You may not use this file except in compliance 7 * with the License. 8 * 9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE 10 * or http://www.opensolaris.org/os/licensing. 11 * See the License for the specific language governing permissions 12 * and limitations under the License. 13 * 14 * When distributing Covered Code, include this CDDL HEADER in each 15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE. 16 * If applicable, add the following below this CDDL HEADER, with the 17 * fields enclosed by brackets "[]" replaced with your own identifying 18 * information: Portions Copyright [yyyy] [name of copyright owner] 19 * 20 * CDDL HEADER END 21 */ 22 /* Copyright (c) 1988 AT&T */ 23 /* All Rights Reserved */ 24 25 26 /* 27 * Copyright 2004 Sun Microsystems, Inc. All rights reserved. 28 * Use is subject to license terms. 29 */ 30 31 #pragma ident "%Z%%M% %I% %E% SMI" 32 33 /* 34 * Binary search algorithm, generalized from Knuth (6.2.1) Algorithm B. 35 */ 36 37 #if !defined(_BOOT) && !defined(_KMDB) 38 #include "synonyms.h" 39 #endif /* !_BOOT && !_KMDB */ 40 #include <stddef.h> 41 #include <stdlib.h> 42 #include <sys/types.h> 43 44 void * 45 bsearch(const void *ky, /* Key to be located */ 46 const void *bs, /* Beginning of table */ 47 size_t nel, /* Number of elements in the table */ 48 size_t width, /* Width of an element (bytes) */ 49 int (*compar)(const void *, const void *)) /* Comparison function */ 50 { 51 char *base; 52 ssize_t two_width; 53 char *last; /* Last element in table */ 54 55 if (nel == 0) 56 return (NULL); 57 58 base = (char *)bs; 59 two_width = width + width; 60 last = base + width * (nel - 1); 61 62 while (last >= base) { 63 64 char *p = base + width * ((last - base)/two_width); 65 int res = (*compar)(ky, (void *)p); 66 67 if (res == 0) 68 return (p); /* Key found */ 69 if (res < 0) 70 last = p - width; 71 else 72 base = p + width; 73 } 74 return (NULL); /* Key not found */ 75 } 76