Find minimum difference between any two elements | C ++ program to find minimum difference between any pair in an unsorted array ; Returns minimum difference between any pair ; Sort array in non - decreasing order ; Initialize difference as infinite ; Find the min diff by comparing adjacent pairs in sorted array ; Return min diff ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinDiff ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int diff = INT_MAX ; for ( int i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i + 1 ] - arr [ i ] < diff ) diff = arr [ i + 1 ] - arr [ i ] ; return diff ; } int main ( ) { int arr [ ] = { 1 , 5 , 3 , 19 , 18 , 25 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum ▁ difference ▁ is ▁ " << findMinDiff ( arr , n ) ; return 0 ; }