//C has no find: a loop returns the index of the value or -1
int indexOf(const int arr[], size_t count, int value) {
for (size_t i = 0; i < count; i++) {
if (arr[i] == value) {
return (int)i;
}
}
return -1;
}
int compareInts(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
return (x > y) - (x < y);
}
int numbers[] = {2, 3, 5, 7, 11, 13, 17};
size_t count = sizeof numbers / sizeof numbers[0];
bool contain5 = indexOf(numbers, count, 5) != -1;
//contain5 is true
int index5 = indexOf(numbers, count, 5);
//index5 is 2
bool contain10 = indexOf(numbers, count, 10) != -1;
//contain10 is false
//in a sorted array bsearch finds by halving the range;
//it returns a pointer to the element or nullptr
int key = 11;
int *found = bsearch(&key, numbers, count, sizeof numbers[0], compareInts);
int index11 = found != nullptr ? (int)(found - numbers) : -1;
//index11 is 4
printf("contain5 is %s\n", contain5 ? "true" : "false");
printf("index5 is %d\n", index5);
printf("contain10 is %s\n", contain10 ? "true" : "false");
printf("index11 is %d\n", index11);