text: Arrange given numbers to form the smallest number | Utility function to print the contents of an array ; A comparison function that return true if ' AB ' is smaller than ' BA ' when we concatenate two numbers ' A ' and ' B ' For example , it will return true if we pass 12 and 24 as arguments . This function will be used by sort ( ) function ; Convert first number to string format ; Convert second number to string format ; Check if ' AB ' is smaller or ' BA ' and return bool value since comparison operator ' < = ' returns true or false ; Function to print the arrangement with the smallest value ; If we pass the name of the comparison function it will sort the array according to the compare function Sort using compare function which is defined above ; Print the sorted array ; Driver code
code: function printArr ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] ) ; } function compare ( num1 , num2 ) { let A = num1 . toString ( ) ; let B = num2 . toString ( ) ; return ( A + B ) . localeCompare ( B + A ) ; } function printSmallest ( N , arr ) { for ( let i = 0 ; i < N ; i ++ ) { for ( let j = i + 1 ; j < N ; j ++ ) { if ( compare ( arr [ i ] , arr [ j ] ) > 0 ) { let temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } } } printArr ( arr , N ) ; } let arr = [ 5 , 6 , 2 , 9 , 21 , 1 ] ; let N = arr . length ; printSmallest ( N , arr ) ;