1 /* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #include <stdlib.h>
16
bsearch(const void * key,const void * base,size_t num_elems,size_t size,int (* compare)(const void *,const void *))17 void *bsearch(const void *key, const void *base, size_t num_elems, size_t size,
18 int (*compare)(const void *, const void *)) {
19 size_t low = 0, high = num_elems - 1;
20
21 if (num_elems == 0) {
22 return NULL;
23 }
24
25 for (;;) {
26 size_t mid = low + ((high - low) / 2);
27 const void *mid_elem = ((unsigned char *) base) + mid*size;
28 int r = compare(key, mid_elem);
29
30 if (r < 0) {
31 if (mid == 0) {
32 return NULL;
33 }
34 high = mid - 1;
35 } else if (r > 0) {
36 low = mid + 1;
37 if (low < mid || low > high) {
38 return NULL;
39 }
40 } else {
41 return (void *) mid_elem;
42 }
43 }
44 }
45