Answer to Question #275229 in C++ for MRM

Question #275229

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 


1
Expert's answer
2021-12-04T01:28:00-0500
#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;
}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment