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: using System ; using System . Collections . Generic ; class GFG { public class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void findPairs ( int [ ] arr , int n , int k , int d ) { if ( n < 2 * k ) { Console . Write ( - 1 ) ; return ; } List < pair > pairs = new List < pair > ( ) ; Array . Sort ( arr ) ; for ( int i = 0 ; i < k ; i ++ ) { if ( arr [ n - k + i ] - arr [ i ] >= d ) { pair p = new pair ( arr [ i ] , arr [ n - k + i ] ) ; pairs . Add ( p ) ; } } if ( pairs . Count < k ) { Console . Write ( - 1 ) ; return ; } foreach ( pair v in pairs ) { Console . WriteLine ( " ( " + v . first + " , ▁ " + v . second + " ) " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , 6 , 10 , 23 , 14 , 7 , 2 , 20 , 9 } ; int n = arr . Length ; int k = 4 , d = 3 ; findPairs ( arr , n , k , d ) ; } }