Answer to Question #275443 in C for mamun

Question #275443

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-07T09:21:14-0500


#include <stdio.h>
 
int binary_search(int arr[], int item, int i, int n)
{
    if (i >= item) {
        int mid_pos = item + (i - item) / 2;
 
       
        if (arr[mid_pos] == n)
            return mid_pos;
 
        
        if (arr[mid_pos] > n)
            return binary_search(arr, item, mid_pos - 1, n);
 
        
        return binary_search(arr, mid_pos + 1,i, n);
    }
 
   
    return -1;
}
 
int main()
{
  int  arr[] = {1,2,3,4,6};
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 6;
    int result = binary_search(arr, 0, n - 1, K);
    (result == -1)
        ? printf("Not present in array")
        : printf("Output %d", 1);
    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

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS