Advertisement
Guest User

binary search

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