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
def printMinDiffPairs ( arr , n ) : NEW_LINE INDENT if n <= 1 : return NEW_LINE arr . sort ( ) NEW_LINE minDiff = arr [ 1 ] - arr [ 0 ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT minDiff = min ( minDiff , arr [ i ] - arr [ i - 1 ] ) NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] ) == minDiff : NEW_LINE INDENT print ( " ( " + str ( arr [ i - 1 ] ) + " , ▁ " + str ( arr [ i ] ) + " ) , ▁ " , end = ' ' ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 5 , 3 , 2 , 4 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE printMinDiffPairs ( arr , n ) NEW_LINE