Initial Commit
[libctiny.git] / bsearch.c
blob1f80d8c511b28d93e7668379891c184151561e0d
1 #include "libctiny.h"
2 #include <windows.h>
4 /***
5 *bsearch.c - do a binary search
7 * Copyright (c) Microsoft Corporation. All rights reserved.
9 *Purpose:
10 * defines bsearch() - do a binary search an an array
12 *******************************************************************************/
14 // #include <cruntime.h>
15 // #include <stdlib.h>
16 // #include <search.h>
18 /***
19 *char *bsearch() - do a binary search on an array
21 *Purpose:
22 * Does a binary search of a sorted array for a key.
24 *Entry:
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
32 * array elements.
34 *Exit:
35 * if key is found:
36 * returns pointer to occurrence of key in array
37 * if key is not found:
38 * returns NULL
40 *Exceptions:
42 *******************************************************************************/
44 void * __cdecl bsearch (
45 const void *key,
46 const void *base,
47 size_t num,
48 size_t width,
49 int (__cdecl *compare)(const void *, const void *)
52 register char *lo = (char *)base;
53 register char *hi = (char *)base + (num - 1) * width;
54 register char *mid;
55 size_t half;
56 int result;
58 while (lo <= hi)
59 if (half = num / 2)
61 mid = lo + (num & 1 ? half : (half - 1)) * width;
62 if (!(result = (*compare)(key,mid)))
63 return(mid);
64 else if (result < 0)
66 hi = mid - width;
67 num = num & 1 ? half : half-1;
69 else {
70 lo = mid + width;
71 num = half;
74 else if (num)
75 return((*compare)(key,lo) ? NULL : lo);
76 else
77 break;
79 return(NULL);