Find k pairs with smallest sums in two arrays | Set 2 | Function to print the K smallest pairs ; if k is greater than total pairs ; _pair _one keeps track of ' first ' in a1 and ' second ' in a2 in _two , _two [ 0 ] keeps track of element in the a2 [ ] and _two [ 1 ] in a1 [ ] ; Repeat the above process till all K pairs are printed ; when both the pointers are pointing to the same elements ( point 3 ) ; updates according to step 1 ; see point 2 ; updates opposite to step 1 ; updates according to rule 1 ; see point 2 ; updates opposite to rule 1 ; see point 2 ; else update as necessary ( point 1 ) ; updating according to rule 1 ; see point 2 ; updating according to rule 1 ; see point 2 ; updating according to rule 1 ; see point 2 ; updating according to rule 1 ; see point 2 ; Driver Code
function printKPairs ( a1 , a2 , size1 , size2 , k ) { if ( k > ( size2 * size1 ) ) { document . write ( " " ) ; return ; } let _one = [ 0 , 0 ] ; let _two = [ 0 , 0 ] ; let cnt = 0 ; while ( cnt < k ) { if ( _one [ 0 ] == _two [ 1 ] && _two [ 0 ] == _one [ 1 ] ) { if ( a1 [ _one [ 0 ] ] < a2 [ _one [ 1 ] ] ) { document . write ( " " + a1 [ _one [ 0 ] ] + " " + a2 [ _one [ 1 ] ] + " " ) ; _one [ 1 ] = ( _one [ 1 ] + 1 ) % size2 ; if ( _one [ 1 ] == 0 ) _one [ 0 ] = ( _one [ 0 ] + 1 ) % size1 ; _two [ 1 ] = ( _two [ 1 ] + 1 ) % size2 ; if ( _two [ 1 ] == 0 ) _two [ 0 ] = ( _two [ 0 ] + 1 ) % size2 ; } else { document . write ( " " + a2 [ _one [ 1 ] ] + " " + a1 [ _one [ 0 ] ] + " " ) ; _one [ 0 ] = ( _one [ 0 ] + 1 ) % size1 ; if ( _one [ 0 ] == 0 ) _one [ 1 ] = ( _one [ 1 ] + 1 ) % size2 ; _two [ 0 ] = ( _two [ 0 ] + 1 ) % size2 ; if ( _two [ 0 ] == 0 ) _two [ 1 ] = ( _two [ 1 ] + 1 ) % size1 ; } } else if ( a1 [ _one [ 0 ] ] + a2 [ _one [ 1 ] ] <= a2 [ _two [ 0 ] ] + a1 [ _two [ 1 ] ] ) { if ( a1 [ _one [ 0 ] ] < a2 [ _one [ 1 ] ] ) { document . write ( " " + a1 [ _one [ 0 ] ] + " " + a2 [ _one [ 1 ] ] + " " ) ; _one [ 1 ] = ( ( _one [ 1 ] + 1 ) % size2 ) ; if ( _one [ 1 ] == 0 ) _one [ 0 ] = ( _one [ 0 ] + 1 ) % size1 ; } else { document . write ( " " + a2 [ _one [ 1 ] ] + " " + a1 [ _one [ 0 ] ] + " " ) ; _one [ 0 ] = ( ( _one [ 0 ] + 1 ) % size1 ) ; if ( _one [ 0 ] == 0 ) _one [ 1 ] = ( _one [ 1 ] + 1 ) % size2 ; } } else if ( a1 [ _one [ 0 ] ] + a2 [ _one [ 1 ] ] > a2 [ _two [ 0 ] ] + a1 [ _two [ 1 ] ] ) { if ( a2 [ _two [ 0 ] ] < a1 [ _two [ 1 ] ] ) { document . write ( " " + a2 [ _two [ 0 ] ] + " " + a1 [ _two [ 1 ] ] + " " ) ; _two [ 0 ] = ( ( _two [ 0 ] + 1 ) % size2 ) ; if ( _two [ 0 ] == 0 ) _two [ 1 ] = ( _two [ 1 ] + 1 ) % size1 ; } else { document . write ( " " + a1 [ _two [ 1 ] ] + " " + a2 [ _two [ 0 ] ] + " " ) ; _two [ 1 ] = ( ( _two [ 1 ] + 1 ) % size1 ) ; if ( _two [ 1 ] == 0 ) _two [ 0 ] = ( _two [ 0 ] + 1 ) % size1 ; } } cnt ++ ; } } let a1 = [ 2 , 3 , 4 ] ; let a2 = [ 1 , 6 , 5 , 8 ] ; let size1 = a1 . length ; let size2 = a2 . length ; let k = 4 ; printKPairs ( a1 , a2 , size1 , size2 , k ) ;