#include <stdio.h>
#include <stdint.h>
int binary_search(uint8_t *arr, uint8_t n, uint8_t key) {
uint8_t start_index = 0;
uint8_t end_index = n-1;
uint8_t mid_index = start_index+ (end_index - start_index) / 2;
while(start_index<=end_index)
{
if(arr[mid_index]==key)
{
return mid_index;
}
else if(key>arr[mid_index])
{
start_index = mid_index +1;
}
else if(key<arr[mid_index])
{
end_index = mid_index -1;
}
mid_index = start_index + (end_index - start_index) / 2;
}
return -1;
}
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;
}
Input
6 5 10 15 20 25 30 20
Expected Output
3