Modify array by sorting nearest perfect squares of array elements having their digits sorted in decreasing order | Java program for the above approach ; 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
import java . util . * ; class GFG { static void reverse ( char [ ] a ) { int i , n = a . length ; char t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } } static void sortArr ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { String s = Integer . toString ( arr [ i ] ) ; char [ ] str = s . toCharArray ( ) ; Arrays . sort ( str ) ; reverse ( str ) ; String string = new String ( str ) ; arr [ i ] = Integer . parseInt ( string ) ; int sr = ( int ) Math . sqrt ( arr [ i ] ) ; int a = sr * sr ; int b = ( sr + 1 ) * ( sr + 1 ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) arr [ i ] = a ; else arr [ i ] = b ; } Arrays . sort ( arr ) ; for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 29 , 43 , 28 , 12 } ; int N = arr . length ; sortArr ( arr , N ) ; } }