Modify array by sorting nearest perfect squares of array elements having their digits sorted in decreasing order | Function to sort array in ascending order after replacing array elements by nearest perfect square of decreasing order of digits ; Traverse the array of strings ; Convert the current array element to a string ; Sort each string in descending order ; Convert the string to equivalent integer ; Calculate square root of current array element ; Calculate perfect square ; Find the nearest perfect square ; Sort the array in ascending order ; Print the array ; Driver Code
function sortArr ( arr , N ) { for ( var i = 0 ; i < N ; i ++ ) { var num = arr [ i ] ; var s = num . toString ( ) ; var temp = s . split ( " " ) ; temp . sort ( ( a , b ) => b - a ) ; s = temp . join ( " " ) ; arr [ i ] = parseInt ( s ) ; var sr = parseInt ( Math . sqrt ( arr [ i ] ) ) ; var a = sr * sr ; var b = ( sr + 1 ) * ( sr + 1 ) ; if ( arr [ i ] - a < b - arr [ i ] ) arr [ i ] = a ; else arr [ i ] = b ; } arr . sort ( ( a , b ) => a - b ) ; for ( var i = 0 ; i < N ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } var arr = [ 29 , 43 , 28 , 12 ] ; var N = arr . length ; sortArr ( arr , N ) ;