Answer to Question #275429 in C for pothik

Question #275429

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-05T02:15:00-0500
#include <stdio.h>
int main()
{
  int c, first, last, middle, n, k=6;


  n=6;




  int arr[6]={1,2,3,4,5,6};


  first = 0;
  last = n - 1;
  middle = (first+last)/2;


  while (first <= last) {
    if (arr[middle] <k)
      first = middle + 1;
    else if (arr[middle] ==k) {
      printf("%d found at location %d.\n", k, middle+1);
      break;
    }
    else
      last = middle - 1;


    middle = (first + last)/2;
  }
  if (first > last)
    printf("Not found! %d isn't present in the list.\n",k);


  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