Binary Search

QUESTION

Write a c program to implement Binary Search.\n\nInput:\nFirst line of the input is the number of elements\nFrom Second line of the input elements of the list\nThe element to be searched is in last line \nRefer the TestCases for the input and output format.

“TESTCASE_1”: “4\n11 22 33 44\n22\n###—###SEPERATOR—###—\n22 found at location 2”, “TESTCASE_2”: “5\n11 22 33 44 55\n10\n###—###SEPERATOR—###—\nNot found”, “TESTCASE_3”: “6\n11 22 33 44 55 66\n55\n###—###SEPERATOR—###—\n55 found at location 5”, “TESTCASE_4”: “7\n1 2 3 4 5 6 7\n16\n###—###SEPERATOR—###—\nNot found”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <stdio.h>
 
int main()
{
   int c, first, last, middle, n, search, array[100];

   scanf("%d",&n);

 
   for (c = 0; c < n; c++)
      scanf("%d",&array[c]);
 
   scanf("%d", &search);
 
   first = 0;
   last = n - 1;
   middle = (first+last)/2;
 
   while (first <= last) {
      if (array[middle] < search)
         first = middle + 1;    
      else if (array[middle] == search) {
         printf("%d found at location %d", search, middle+1);
         break;
      }
      else
         last = middle - 1;
 
      middle = (first + last)/2;
   }
   if (first > last)
      printf("Not found");
 
   return 0;   
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro