stdlib: optimize bsearch()

... by checking most probable condition first (elements do differ)

Change-Id: I424eab9c32a6d9eb82b686ca04025ec8c9097035
Signed-off-by: André Goddard Rosa <andre.goddard@gmail.com>
This commit is contained in:
André Goddard Rosa 2010-03-28 21:18:56 -03:00
parent 4ad72f89b1
commit acdb052030

View File

@ -56,11 +56,11 @@ bsearch(const void *key, const void *base0, size_t nmemb, size_t size,
for (lim = nmemb; lim != 0; lim >>= 1) { for (lim = nmemb; lim != 0; lim >>= 1) {
p = base + (lim >> 1) * size; p = base + (lim >> 1) * size;
cmp = (*compar)(key, p); cmp = (*compar)(key, p);
if (cmp == 0)
return ((void *)p);
if (cmp > 0) { /* key > p: move right */ if (cmp > 0) { /* key > p: move right */
base = (char *)p + size; base = (char *)p + size;
lim--; lim--;
} else if (cmp == 0) {
return ((void *)p);
} /* else move left */ } /* else move left */
} }
return (NULL); return (NULL);