Closest numbers from a list of unsorted integers | C # program to find minimum difference an unsorted array . ; 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
using System ; class GFG { static void printMinDiffPairs ( int [ ] arr , int n ) { if ( n <= 1 ) return ; Array . Sort ( arr ) ; int minDiff = arr [ 1 ] - arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) minDiff = Math . Min ( minDiff , arr [ i ] - arr [ i - 1 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( ( arr [ i ] - arr [ i - 1 ] ) == minDiff ) { Console . Write ( " ▁ ( " + arr [ i - 1 ] + " , ▁ " + arr [ i ] + " ) , ▁ " ) ; } } } public static void Main ( ) { int [ ] arr = { 5 , 3 , 2 , 4 , 1 } ; int n = arr . Length ; printMinDiffPairs ( arr , n ) ; } }