Answer to Question #275304 in C for Lucky

Question #275304

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-04T10:42:26-0500
#include <stdio.h>

int bin_search(int *arr, int n, int target) {
  int l = 0, r = n;
  while (l < r) {
    int m = (l + r) / 2;
    if (arr[m] == target) return m;
    if (arr[m]  < target) r = m;
    if (arr[m]  > target) l = m;
  }
  return -1;
}

int main() {
  int arr[5] {1, 2, 3, 4, 6};
  int k = 6;
  int i = bin_search(arr, 5, k);
  if (i != -1) printf("Item found at position %d", i);
  else printf("Item not found!");
}

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