Replace each element of Array with it 's corresponding rank | Java program for the above approach ; Function to assign rank to array elements ; Copy input array into newArray ; Sort newArray [ ] in ascending order ; Map to store the rank of the array element ; Update rank of element ; Assign ranks to elements ; Driver Code ; Given array arr [ ] ; Function Call ; Print the array elements
import java . util . * ; class GFG { static void changeArr ( int [ ] input ) { int newArray [ ] = Arrays . copyOfRange ( input , 0 , input . length ) ; Arrays . sort ( newArray ) ; int i ; Map < Integer , Integer > ranks = new HashMap < > ( ) ; int rank = 1 ; for ( int index = 0 ; index < newArray . length ; index ++ ) { int element = newArray [ index ] ; if ( ranks . get ( element ) == null ) { ranks . put ( element , rank ) ; rank ++ ; } } for ( int index = 0 ; index < input . length ; index ++ ) { int element = input [ index ] ; input [ index ] = ranks . get ( input [ index ] ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 100 , 2 , 70 , 2 } ; changeArr ( arr ) ; System . out . println ( Arrays . toString ( arr ) ) ; } }