Last active
October 30, 2024 10:28
-
-
Save vurtun/100f3eee6c7f8ec1cbe9b6506f3cfddd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static inline int | |
bin_search(const void *vals, int cnt, int siz, void *val, | |
int(*cmp_less)(const void *a, const void *b)) { | |
int half, nleft = cnt; | |
const unsigned char *base = vals; | |
while ((half = (nleft >> 1)) > 0) { | |
const unsigned char *mid = base + half * siz; | |
base = cmp_less(mid, val) ? mid : base; | |
nleft -= half; | |
} | |
base += (nleft == 1 && cmp_less(base, val)) ? siz : 0; | |
return (base - (unsigned char*)(vals))/siz; | |
} | |
#include <stdio.h> | |
#include <stdlib.h> | |
static inline int | |
cmp_less(const void *a, const void *b) { | |
return *(int*)a < *(int*)b; | |
} | |
extern int | |
main(int argc, char **argv) { | |
int a[64]; | |
for ( int i = 2; i < argc; ++i) { | |
a[i] = atoi(argv[i]); | |
} | |
int x = atoi(argv[1]); | |
int elm = bin_search(a, argc-1, sizeof(int), &x, cmp_less); | |
printf("%d\n", elm); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment