Advertisement
GanadiniAkshay

binary search

Aug 31st, 2014
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.72 KB | None | 0 0
  1. //PROGRAM TO DO BINARY SEARCH
  2.  
  3. #include <stdio.h>
  4.  
  5. int main()
  6. {
  7.     int size,i,key;
  8.     printf("Enter the size of array: \n");
  9.     scanf("%d",&size);
  10.     int numbers[size];
  11.     printf("Enter the numbers in sorted order: \n");
  12.     for(i=0;i<size;i++)
  13.     {
  14.         printf("\nEnter number %d: ",i+1);
  15.         scanf("%d",&numbers[i]);
  16.     }
  17.     printf("\nEnter the key to search for: ");
  18.     scanf("%d",&key);
  19.  
  20.     int low=0,high=size;
  21.     while(low<high)
  22.     {
  23.         int mid = (low+high)/2;
  24.         if (numbers[mid] == key)
  25.         {
  26.             printf("The key was found at %d position.",mid+1);
  27.             return 0;
  28.         }
  29.         else if(numbers[mid]<key)
  30.         {
  31.             low = mid+1;
  32.         }
  33.         else if(numbers[mid]>key)
  34.         {
  35.             high = mid-1;
  36.         }
  37.     }
  38.    
  39.     printf("\nThe key was not found");
  40.     return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement