Convert an array to reduced form | Set 1 ( Simple and Hashing ) | Java Program to convert an Array to reduced form ; Create a temp array and copy contents of arr [ ] to temp ; Sort temp array ; Create a hash table . ; One by one insert elements of sorted temp [ ] and assign them values from 0 to n - 1 ; Convert array by taking positions from umap ; Driver code
import java . util . * ; class GFG { public static void convert ( int arr [ ] , int n ) { int temp [ ] = arr . clone ( ) ; Arrays . sort ( temp ) ; HashMap < Integer , Integer > umap = new HashMap < > ( ) ; int val = 0 ; for ( int i = 0 ; i < n ; i ++ ) umap . put ( temp [ i ] , val ++ ) ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = umap . get ( arr [ i ] ) ; } public static void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 20 , 15 , 12 , 11 , 50 } ; int n = arr . length ; System . out . println ( " Given ▁ Array ▁ is ▁ " ) ; printArr ( arr , n ) ; convert ( arr , n ) ; System . out . println ( " Converted Array is "); printArr ( arr , n ) ; } }