text: Find k ordered pairs in array with minimum difference d | C ++ implementation of the approach ; Function to find the required pairs ; There has to be atleast 2 * k elements ; To store the pairs ; Sort the given array ; For every possible pair ; If the current pair is valid ; Insert it into the pair vector ; If k pairs are not possible ; Print the pairs ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPairs ( int arr [ ] , int n , int k , int d ) { if ( n < 2 * k ) { cout << -1 ; return ; } vector < pair < int , int > > pairs ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < k ; i ++ ) { if ( arr [ n - k + i ] - arr [ i ] >= d ) { pair < int , int > p = make_pair ( arr [ i ] , arr [ n - k + i ] ) ; pairs . push_back ( p ) ; } } if ( pairs . size ( ) < k ) { cout << -1 ; return ; } for ( auto v : pairs ) { cout << " ( " << v . first << " , ▁ " << v . second << " ) " << endl ; } } int main ( ) { int arr [ ] = { 4 , 6 , 10 , 23 , 14 , 7 , 2 , 20 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 4 , d = 3 ; findPairs ( arr , n , k , d ) ; return 0 ; }