Advertisement
JayaAhmed

Binary Search

Jul 5th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.85 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.     int c, first, last, middle, n, search, array[100];
  6.  
  7.     printf("Enter number of elements : ");
  8.     scanf("%d",&n);
  9.  
  10.     printf("Enter %d integers : ", n);
  11.  
  12.     for (c = 0; c < n; c++)
  13.         scanf("%d",&array[c]);
  14.  
  15.     printf("Enter value to find : ");
  16.     scanf("%d", &search);
  17.  
  18.     first = 0;
  19.     last = n - 1;
  20.     middle = (first+last)/2;
  21.  
  22.     while (first <= last)
  23.     {
  24.         if (array[middle] == search)
  25.         {
  26.             printf("%d found at location %d.\n", search, middle+1);
  27.             break;
  28.         }
  29.  
  30.         else if (array[middle] < search)
  31.             first = middle + 1;
  32.  
  33.         else
  34.             last = middle - 1;
  35.  
  36.         middle = (first + last)/2;
  37.     }
  38.     if (first > last)
  39.         printf("Not found! %d is not present in the list.\n", search);
  40.  
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement