Advertisement
Guest User

Binary search

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