fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Scanner sc = new Scanner(System.in);
  13. int n = sc.nextInt();
  14. int x = sc.nextInt();
  15.  
  16. int[] a = new int[n];
  17.  
  18. for(int i=0; i<n; i++){
  19. a[i] = sc.nextInt();
  20. }
  21.  
  22. int lo = -1;
  23. int hi = n;
  24.  
  25. while(lo +1 < hi){
  26. int mid = lo + ( hi - lo)/2;
  27. if(a[mid]==x){
  28. System.out.println("x already exists! " + x);
  29. return;
  30. }
  31. if(a[mid]<x){
  32. lo = mid;
  33. } else {
  34. hi = mid;
  35. }
  36. }
  37. if(lo == -1){
  38. System.out.println("Only greater values exist in array! "+ a[hi]);
  39. return;
  40. }
  41. if(hi == n){
  42. System.out.println("Only smaller values exist in array! "+ a[lo]);
  43. return;
  44. }
  45.  
  46. int ans = (x - a[lo] < a[hi] - x) ? a[lo] : a[hi];
  47. System.out.println("Closest value to "+ x +" is "+ ans);
  48. return;
  49. }
  50. }
Success #stdin #stdout 0.13s 58860KB
stdin
5 16
1 3 5 8 11
stdout
Only smaller values exist in array! 11