Skip to content

Instantly share code, notes, and snippets.

@bjourne
Created August 11, 2023 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjourne/c1411304d211408bd9bc398e1f86509d to your computer and use it in GitHub Desktop.
Save bjourne/c1411304d211408bd9bc398e1f86509d to your computer and use it in GitHub Desktop.
Fast and slow (?) bsearch
static uint32_t *
fast_bsearch_u32(uint32_t *base, size_t nmemb, uint32_t key) {
while (nmemb) {
size_t half = nmemb >> 1;
if (base[half] < key) {
base += nmemb - half;
}
nmemb = half;
}
return base;
}
static uint32_t *
slow_bsearch_u32(uint32_t *base, size_t nmemb, uint32_t key) {
while (nmemb) {
size_t half = nmemb >> 1;
if (base[half] < key) {
base += half + 1;
nmemb -= half + 1;
} else {
nmemb = half;
}
}
return base;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment