#include <stdio.h>
#include <stdint.h>
int binary_search(uint8_t *arr, uint8_t n, uint8_t key) {
// Your logic here
// let array be 5,10,15,20,25,30 and key is 20
int low = 0, high = n-1;//5
while(low<=high){//t t
int mid = (low + high) / 2;//2 3
if(arr[mid]==key)//f t
return mid;//3
else if(arr[mid]<key)//t
low = mid + 1;//1
else
high = mid - 1;
}
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);//3
return 0;
}n: number of elements in the arrayarr[]: a sorted array of n unsigned 8-bit integerskey: the value to search forlow = 0 (start of array)high = n - 1 (end of array)low <= high:mid = (low + high) / 2arr[mid] == key: return mid (key found)arr[mid] < key: search right half โ low = mid + 1arr[mid] > key: search left half โ high = mid - 1-1 (key not found)Input:
n = 6
arr = [5, 10, 15, 20, 25, 30]
key = 20
Steps:
Output:
3
Input
6 5 10 15 20 25 30 20
Expected Output
3