Find minimum difference between any two elements | Java 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 method to test the above function
import java . util . Arrays ; class GFG { static int findMinDiff ( int [ ] arr , int n ) { Arrays . sort ( arr ) ; int diff = Integer . MAX_VALUE ; for ( int i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i + 1 ] - arr [ i ] < diff ) diff = arr [ i + 1 ] - arr [ i ] ; return diff ; } public static void main ( String [ ] args ) { int arr [ ] = new int [ ] { 1 , 5 , 3 , 19 , 18 , 25 } ; System . out . println ( " Minimum ▁ difference ▁ is ▁ " + findMinDiff ( arr , arr . length ) ) ; } }