* Perform a binary search. * * The code below is a bit sneaky. After a comparison fails, we * divide the work in half by moving either left or right. If lim * is odd, moving left simply involves halving lim: e.g., when lim * is 5 we look at item 2, so we change lim to 2 so that we will * look at items 0 & 1. If lim is even, the same applies. If lim * is odd, moving right again involes ha
| 55 | * look at item 3. |
| 56 | */ |
| 57 | void * |
| 58 | bsearch(const void *key, const void *base0, size_t nmemb, size_t size, |
| 59 | int (*compar)(const void *, const void *)) |
| 60 | { |
| 61 | const char *base = base0; |
| 62 | size_t lim; |
| 63 | int cmp; |
| 64 | const void *p; |
| 65 | |
| 66 | for (lim = nmemb; lim != 0; lim >>= 1) { |
| 67 | p = base + (lim >> 1) * size; |
| 68 | cmp = (*compar)(key, p); |
| 69 | if (cmp == 0) |
| 70 | return ((void *)(uintptr_t)p); |
| 71 | if (cmp > 0) { /* key > p: move right */ |
| 72 | base = (const char *)p + size; |
| 73 | lim--; |
| 74 | } /* else move left */ |
| 75 | } |
| 76 | return (NULL); |
| 77 | } |
no outgoing calls
no test coverage detected