Skip to content

Instantly share code, notes, and snippets.

@fcole90
Last active July 14, 2023 19:45
Show Gist options
  • Select an option

  • Save fcole90/7165abea8faab8011d7c4fdf1920ff7a to your computer and use it in GitHub Desktop.

Select an option

Save fcole90/7165abea8faab8011d7c4fdf1920ff7a to your computer and use it in GitHub Desktop.
Simple generic bisect
#include <stdio.h>
#define array_len(x) ((sizeof (x) == 0) ? (0) : (sizeof (x) / sizeof (x[0])))
char *my_word_list[] = {
"abc",
"bcd",
"def",
"fgh"
};
int my_int_list[] = {
7,
12,
16,
17,
32,
45,
46,
48
};
int before_by_int(int *a, int *b) {
return *b - *a;
}
int before_by_str(char *a, char *b) {
char *_a = a;
char *_b = b;
char a_value;
char b_value;
while (1) {
if (!*_a && !*_b) {
return 0;
}
if (!*_a) {
return (int) *_b;
}
if (!*_b) {
return (int) -*_a;
}
a_value = *_a;
b_value = *_b;
if (a_value != b_value) {
return (int) b_value - a_value;
}
_a++;
_b++;
}
return *b - *a;
}
int bisect(void* element, void* a_list[], int list_len, int (*compare)(void* a, void* b)) {
int start = 0;
int end = list_len;
int position = 0;
void* found = 0;
int compare_result = 0;
while (1) {
position = (end - start) / 2 + start;
found = a_list[position];
compare_result = compare(found, element);
if (compare_result == 0) {
return position;
}
if (position <= start || position >= end) {
return -1;
}
if (compare_result > 0) {
start = position;
continue;
}
end = position;
}
}
int main()
{
char *my_string = "bcd";
int my_list_len = array_len(my_word_list);
for (int i = 0; i < my_list_len; i++) {
printf("%d: %s\n", i, my_word_list[i]);
}
int element_index = bisect(
(void*) my_string,
(void**) my_word_list,
my_list_len,
(int (*) (void*, void*)) before_by_str
);
printf("Bisect index: %d\n", element_index);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment