Advertisement
namkongkirat

Binary Searching Algorithm

Aug 1st, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.64 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int binarysearch (int arr[], int high, int low, int key)
  4. {
  5.     int mid;
  6.     while (high >= low)
  7.     {
  8.         mid = (high + low) / 2;
  9.        
  10.         if(arr[mid] == key)
  11.         {
  12.             return mid + 1;
  13.         }
  14.        
  15.         else if( key > arr[mid])
  16.         {
  17.             low = mid + 1;
  18.         }
  19.        
  20.         else
  21.         {
  22.             high = mid - 1;
  23.         }
  24.     }
  25.     return -1;
  26. }
  27.  
  28. int main()
  29. {
  30.     int key, loc;
  31.     int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  32.     printf("Enter the Key: ");
  33.     scanf("%d",&key);
  34.     loc = binarysearch (a, 9, 0, key);
  35.     if (loc == -1)
  36.     {
  37.         printf("Search Unsuccessful. Input a correct key.\n");
  38.     }
  39.     else
  40.     {
  41.         printf("The location of Key %d is %d", key, loc);
  42.     }
  43.     getch();
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement