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 binary(int arr[], int element, int r, int x)
{
if (r >= element) {
int midPosition = element + (r - element) / 2;
if (arr[midPosition] == x)
return midPosition;
if (arr[midPosition] > x)
return binary(arr, element, midPosition - 1, x);
return binary(arr, midPosition + 1, r, x);
}
return -1;
}
int main()
{
int arr[] = {1,2,3,4,6};
int n = sizeof(arr) / sizeof(arr[0]);
int K = 6;
int result = binary(arr, 0, n - 1, K);
(result == -1)
? printf("Not present in array")
: printf("Output %d", 1);
return 0;
}
Comments
Leave a comment