Closest numbers from a list of unsorted integers | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMinDiffPairs ( int arr [ ] , int n ) { if ( n <= 1 ) return ; sort ( arr , arr + n ) ; int minDiff = arr [ 1 ] - arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) minDiff = min ( minDiff , arr [ i ] - arr [ i - 1 ] ) ; for ( int i = 1 ; i < n ; i ++ ) if ( ( arr [ i ] - arr [ i - 1 ] ) == minDiff ) cout << " ( " << arr [ i - 1 ] << " , ▁ " << arr [ i ] << " ) , ▁ " ; } int main ( ) { int arr [ ] = { 5 , 3 , 2 , 4 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printMinDiffPairs ( arr , n ) ; return 0 ; }