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 <iostream>
using namespace std;
// This is a Function to find insert position of value K
int f_index(int arr[], int n=5, int K)
{
// Traverse the array
for (int i = 0; i < n; i++)
// If K is found
if (arr[i] == K)
return i;
// If current array element
// exceeds K
else if (arr[i] > K)
return i;
// If all elements are smaller
// than K
return n;
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 3, 4, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
int K = 6;
cout << f_index(arr, n, K) << endl;
return 0;
}
Comments
Leave a comment