#include <stdio.h>
#include <stdint.h>
int binary_search(uint8_t *arr, uint8_t n, uint8_t key) {
// Your logic here
uint8_t s = 0;
uint8_t e = n;
uint8_t m = 0;
int ret = -1;
while (s < e) {
m = (s + e) / 2;
if (arr[m] == key) {
ret = m;
break;
} else if (arr[m] < key) {
s = m;
} else {
e = m;
}
}
return ret;
}
int main() {
uint8_t n, key;
scanf("%hhu", &n);
uint8_t arr[100];
for (uint8_t i = 0; i < n; i++) {
scanf("%hhu", &arr[i]);
}
scanf("%hhu", &key);
int index = binary_search(arr, n, key);
printf("%d", index);
return 0;
}
Solving Approach
it should be sorted array to search with binary search