Closest numbers from a list of unsorted integers | Returns minimum difference between any two pair in arr [ 0. . n - 1 ] ; Sort array elements ; Compare differences of adjacent pairs to find the minimum difference . ; Traverse array again and print all pairs with difference as minDiff . ; Driver code
function printMinDiffPairs ( arr , n ) { if ( n <= 1 ) return ; arr . sort ( ) ; let minDiff = arr [ 1 ] - arr [ 0 ] ; for ( let i = 2 ; i < n ; i ++ ) minDiff = Math . min ( minDiff , arr [ i ] - arr [ i - 1 ] ) ; for ( let i = 1 ; i < n ; i ++ ) { if ( ( arr [ i ] - arr [ i - 1 ] ) == minDiff ) { document . write ( " " + arr [ i - 1 ] + " " + arr [ i ] + " " ) ; } } } let arr = [ 5 , 3 , 2 , 4 , 1 ] ; let n = arr . length ; printMinDiffPairs ( arr , n ) ;