fork(1) download
  1. #include <iostream>
  2. #include <climits>
  3. #include <cstdlib>
  4. using namespace std;
  5.  
  6. // Prints the pair with sum cloest to x
  7. void printClosest(int arr[], int n, int x)
  8. {
  9. int res_l, res_r; // To store indexes of result pair
  10.  
  11. // Initialize left and right indexes and difference between
  12. // pair sum and x
  13. int l = 0, r = n-1, diff = INT_MAX;
  14.  
  15. // While there are elements between l and r
  16. while (r > l)
  17. {
  18. // Check if this pair is closer than the closest pair so far
  19. if (abs(arr[l] + arr[r] - x) < diff)
  20. {
  21. res_l = l;
  22. res_r = r;
  23. diff = abs(arr[l] + arr[r] - x);
  24. }
  25.  
  26. // If this pair has more sum, move to smaller values.
  27. if (arr[l] + arr[r] > x)
  28. r--;
  29. else // Move to larger values
  30. l++;
  31. }
  32.  
  33. cout <<" The closest pair is " << arr[res_l] << " and " << arr[res_r];
  34. }
  35.  
  36. // Driver program to test above functions
  37. int main()
  38. {
  39. int arr[] = {10, 22, 28, 29, 32, 45}, x = 54;
  40. int n = sizeof(arr)/sizeof(arr[0]);
  41. printClosest(arr, n, x);
  42. return 0;
  43. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
 The closest pair is 22 and 32