#include <bits/stdc++.h>
using namespace std;
void findpairs(int *a, int n)
{
// sort the array using default sort library function, O(logn) generally
sort(a, a + n);
int temp, i = 0, j = n - 1, minsum = INT_MAX, indexN = i, indexP = j;
while (i < j)
{
// current pair-sum
temp = a[i] + a[j];
// if abs(current pair-sum)<abs(minsum)
if (abs(temp) < abs(minsum))
{
minsum = temp;
indexN = i;
indexP = j;
}
// if current pair-sum<0
if (temp < 0)
{
// Increment i
i++;
}
else
j--; // Decrement j
}
// print the pair
cout << "the pair is " << a[indexN] << "," << a[indexP] << endl;
}
int main()
{
int x, count = 0, n;
// enter array length
cout << "enter no of data\n";
cin >> n;
int *a = (int *)(malloc(sizeof(int) * n));
// fill the array
cout << "enter datas \n";
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
findpairs(a, n);
return 0;
}
Output
enter size of data
6
enter datas
11
-6
4
-7
8
-9
the pair is -9,8
0 Comments