Answer to Question #274800 in C for n hasan

Question #274800

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-03T18:05:52-0500
#include <stdio.h>

int BinaySearch(int arr[], int n, int k) {
    int lo, hi, m;

    lo = 0;
    hi = n-1;

    while (lo <= hi) {
        m = (hi+lo) / 2;
        if (arr[m] == k) {
            return 1;
        }
        if (arr[m] < k) {
            lo = m+1;
        }
        else {
            hi = m-1;
        }
    }
    return 0;
}

int main() {
    int arr[5] = {1, 2, 3, 4, 6};
    int res = BinaySearch(arr, 5, 6);

    printf("%d\n", res);

    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