Advertisement
Idanref

Bin Search

Jan 13th, 2021
1,679
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.67 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <math.h>
  5.  
  6. int bin_search(int *a, int n, int x)
  7. {
  8.     int low, mid, high;
  9.     int sum_left, sum_right;
  10.  
  11.     low = 0;
  12.     high = n - 1;
  13.  
  14.     while(low <= high)
  15.     {
  16.         mid = (high+low) / 2;
  17.         sum_left = a[mid] + a[mid-1];
  18.         sum_right = a[mid] + a[mid+1];
  19.  
  20.         if(sum_left == x)
  21.             return mid-1;
  22.  
  23.         else if(sum_right == x)
  24.             return mid;
  25.  
  26.         else if(sum_right < x)
  27.             low = mid+1;
  28.  
  29.         else if(sum_right > x)
  30.             high = mid-1;
  31.     }
  32.  
  33.     return -1;
  34. }
  35.  
  36. void main()
  37. {
  38.     int a[] = {-3, 8, 1, 9, 15, 10, 18,33,21}; // 5
  39.  
  40.     int result = bin_search(a, 9, 54);
  41.  
  42.     printf("Result %d\n", result);
  43.    
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement