Convert an array to reduced form | Set 1 ( Simple and Hashing ) | C ++ program to convert an array in reduced form ; Create a temp array and copy contents of arr [ ] to temp ; Sort temp array ; Create a hash table . Refer tinyurl . com / zp5wgef http : ; 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 program to test above method
#include <bits/stdc++.h> NEW_LINE using namespace std ; void convert ( int arr [ ] , int n ) { int temp [ n ] ; memcpy ( temp , arr , n * sizeof ( int ) ) ; sort ( temp , temp + n ) ; unordered_map < int , int > umap ; int val = 0 ; for ( int i = 0 ; i < n ; i ++ ) umap [ temp [ i ] ] = val ++ ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = umap [ arr [ i ] ] ; } void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 10 , 20 , 15 , 12 , 11 , 50 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Given ▁ Array ▁ is ▁ STRNEWLINE " ; printArr ( arr , n ) ; convert ( arr , n ) ; cout << " Converted Array is " ; printArr ( arr , n ) ; return 0 ; }