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 bin_search(int *arr, int n, int target) {
int l = 0, r = n;
while (l < r) {
int m = (l + r) / 2;
if (arr[m] == target) return m;
if (arr[m] < target) r = m;
if (arr[m] > target) l = m;
}
return -1;
}
int main() {
int arr[5] {1, 2, 3, 4, 6};
int k = 6;
int i = bin_search(arr, 5, k);
if (i != -1) printf("Item found at position %d", i);
else printf("Item not found!");
}
Comments
Leave a comment