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
< ? php function printMinDiffPairs ( $ arr , $ n ) { if ( $ n <= 1 ) return ; sort ( $ arr ) ; $ minDiff = $ arr [ 1 ] - $ arr [ 0 ] ; for ( $ i = 2 ; $ i < $ n ; $ i ++ ) $ minDiff = min ( $ minDiff , $ arr [ $ i ] - $ arr [ $ i - 1 ] ) ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) if ( ( $ arr [ $ i ] - $ arr [ $ i - 1 ] ) == $ minDiff ) echo " ( " , $ arr [ $ i - 1 ] , " , ▁ " , $ arr [ $ i ] , " ) , ▁ " ; } $ arr = array ( 5 , 3 , 2 , 4 , 1 ) ; $ n = sizeof ( $ arr ) ; printMinDiffPairs ( $ arr , $ n ) ; ? >