text: Find k ordered pairs in array with minimum difference d | 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 leto the pair vector ; If k pairs are not possible ; Print the pairs ; Driver code
code: function findPairs ( arr , n , k , d ) { if ( n < 2 * k ) { document . write ( - 1 ) ; return ; } let pairs = [ ] ; arr . sort ( ( a , b ) => a - b ) ; for ( let i = 0 ; i < k ; i ++ ) { if ( arr [ n - k + i ] - arr [ i ] >= d ) { let p = [ arr [ i ] , arr [ n - k + i ] ] ; pairs . push ( p ) ; } } if ( pairs . length < k ) { document . write ( - 1 ) ; return ; } for ( let v of pairs ) { document . write ( " " + v [ 0 ] + " " + v [ 1 ] + " " + " " ) ; } } let arr = [ 4 , 6 , 10 , 23 , 14 , 7 , 2 , 20 , 9 ] ; let n = arr . length ; let k = 4 , d = 3 ; findPairs ( arr , n , k , d ) ;