5 *bsearch.c - do a binary search
7 * Copyright (c) Microsoft Corporation. All rights reserved.
10 * defines bsearch() - do a binary search an an array
12 *******************************************************************************/
14 // #include <cruntime.h>
15 // #include <stdlib.h>
16 // #include <search.h>
19 *char *bsearch() - do a binary search on an array
22 * Does a binary search of a sorted array for a key.
25 * const char *key - key to search for
26 * const char *base - base of sorted array to search
27 * unsigned int num - number of elements in array
28 * unsigned int width - number of bytes per element
29 * int (*compare)() - pointer to function that compares two array
30 * elements, returning neg when #1 < #2, pos when #1 > #2, and
31 * 0 when they are equal. Function is passed pointers to two
36 * returns pointer to occurrence of key in array
37 * if key is not found:
42 *******************************************************************************/
44 void * __cdecl
bsearch (
49 int (__cdecl
*compare
)(const void *, const void *)
52 register char *lo
= (char *)base
;
53 register char *hi
= (char *)base
+ (num
- 1) * width
;
61 mid
= lo
+ (num
& 1 ? half
: (half
- 1)) * width
;
62 if (!(result
= (*compare
)(key
,mid
)))
67 num
= num
& 1 ? half
: half
-1;
75 return((*compare
)(key
,lo
) ? NULL
: lo
);