Given an array arr[] sorted in ascending order of size N and an integer K. Check if K is present in the array or not. (Use Binary Search) Input: N = 5 K = 6 arr[] = {1,2,3,4,6} Output: 1 Explanation: Since, 6 is present in the array at index 4 (0-based indexing), output is 1
#include <stdio.h>
int BinaySearch(int arr[], int n, int k) {
int lo, hi, m;
lo = 0;
hi = n-1;
while (lo <= hi) {
m = (hi+lo) / 2;
if (arr[m] == k) {
return 1;
}
if (arr[m] < k) {
lo = m+1;
}
else {
hi = m-1;
}
}
return 0;
}
int main() {
int arr[5] = {1, 2, 3, 4, 6};
int res = BinaySearch(arr, 5, 6);
printf("%d\n", res);
return 0;
}
Comments
Leave a comment