Find the closest pair from two sorted arrays | ar1 [ 0. . m - 1 ] and ar2 [ 0. . n - 1 ] are two given sorted arrays and x is given number . This function prints the pair from both arrays such that the sum of the pair is closest to x . ; Initialize the diff between pair sum and x . ; res_l and res_r are result indexes from ar1 [ ] and ar2 [ ] respectively ; Start from left side of ar1 [ ] and right side of ar2 [ ] ; If this pair is closer to x than the previously found closest , then update res_l , res_r and diff ; If sum of this pair is more than x , move to smaller side ; move to the greater side ; Print the result ; driver code
function printClosest ( ar1 , ar2 , m , n , x ) { let diff = Number . MAX_VALUE ; let res_l , res_r ; let l = 0 , r = n - 1 ; while ( l < m && r >= 0 ) { if ( Math . abs ( ar1 [ l ] + ar2 [ r ] - x ) < diff ) { res_l = l ; res_r = r ; diff = Math . abs ( ar1 [ l ] + ar2 [ r ] - x ) ; } if ( ar1 [ l ] + ar2 [ r ] > x ) r -- ; else l ++ ; } document . write ( " " + ar1 [ res_l ] + " " + ar2 [ res_r ] + " " ) ; } let ar1 = [ 1 , 4 , 5 , 7 ] ; let ar2 = [ 10 , 20 , 30 , 40 ] ; let m = ar1 . length ; let n = ar2 . length ; let x = 38 ; printClosest ( ar1 , ar2 , m , n , x ) ;