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
#include <stdio.h>
int main()
{
  int c, first, last, middle, n, k=6;
  n=5;
  int arr[6]={1,2,3,4,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;
}
Comments