Arrange given numbers to form the smallest number | Java implementation of the approach ; Utility function to print the contents of an array ; A comparison function that return negative if ' AB ' is smaller than ' BA ' when we concatenate two numbers ' A ' and ' B ' For example , it will return negative value if we pass 12 and 24 as arguments . This function will be used during sort ; Convert first number to string format ; Convert second number to string format ; Check if ' AB ' is smaller or ' BA ' and return integer value ; Function to print the arrangement with the smallest value ; Sort using compare function which is defined above ; Print the sorted array ; Driver code
class GFG { public static void printArr ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] ) ; } public static int compare ( int num1 , int num2 ) { String A = Integer . toString ( num1 ) ; String B = Integer . toString ( num2 ) ; return ( A + B ) . compareTo ( B + A ) ; } public static void printSmallest ( int N , int [ ] arr ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( compare ( arr [ i ] , arr [ j ] ) > 0 ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } } } printArr ( arr , N ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 6 , 2 , 9 , 21 , 1 } ; int N = arr . length ; printSmallest ( N , arr ) ; } }