fork download
  1. #include <stdio.h>
  2.  
  3. #define nearest(a, x) _nearest(a, sizeof(a) / sizeof(a[0]), x)
  4.  
  5. int _nearest(int a[], int n, int x)
  6. {
  7. int L = 0, C, R = n - 1;
  8.  
  9. while (L + 1 < R) {
  10. C = (L + R) / 2;
  11. a[C] < x ? (L = C) : (R = C);
  12. }
  13.  
  14. return x - a[L] <= a[R] - x ? a[L] : a[R];
  15. }
  16.  
  17. int main(void)
  18. {
  19. int a[] = {98, 100, 198, 200, 250, 298};
  20.  
  21. printf("%d -> %d\n", 50, nearest(a, 50));
  22. printf("%d -> %d\n", 195, nearest(a, 195));
  23.  
  24. return 0;
  25. }
Success #stdin #stdout 0s 4504KB
stdin
Standard input is empty
stdout
50 -> 98
195 -> 198