Sort an Array alphabetically when each number is converted into words | C ++ program to sort an array of integers alphabetically ; Variable to store the word form of units digit and up to twenty ; Variable to store the word form of tens digit ; Function to convert a two digit number to the word by using the above defined arrays ; If n is more than 19 , divide it ; If n is non - zero ; Function to print a given number in words ; Stores the word representation of the given number n ; Handles digits at ten millions and hundred millions places ; Handles digits at hundred thousands and one millions places ; Handles digits at thousands and tens thousands places ; Handles digit at hundreds places ; Call the above function to convert the number into words ; Function to sort the array according to the albhabetical order ; Vector to store the number in words with respective elements ; Inserting number in words with respective elements in vector pair ; Sort the vector , this will sort the pair according to the alphabetical order . ; Print the sorted vector content ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string one [ ] = { " " , " one ▁ " , " two ▁ " , " three ▁ " , " four ▁ " , " five ▁ " , " six ▁ " , " seven ▁ " , " eight ▁ " , " nine ▁ " , " ten ▁ " , " eleven ▁ " , " twelve ▁ " , " thirteen ▁ " , " fourteen ▁ " , " fifteen ▁ " , " sixteen ▁ " , " seventeen ▁ " , " eighteen ▁ " , " nineteen ▁ " } ; string ten [ ] = { " " , " " , " twenty ▁ " , " thirty ▁ " , " forty ▁ " , " fifty ▁ " , " sixty ▁ " , " seventy ▁ " , " eighty ▁ " , " ninety ▁ " } ; string numToWords ( int n , string s ) { string str = " " ; if ( n > 19 ) str += ten [ n / 10 ] + one [ n % 10 ] ; else str += one [ n ] ; if ( n ) str += s ; return str ; } string convertToWords ( int n ) { string out ; out += numToWords ( ( n / 10000000 ) , " crore ▁ " ) ; out += numToWords ( ( ( n / 100000 ) % 100 ) , " lakh ▁ " ) ; out += numToWords ( ( ( n / 1000 ) % 100 ) , " thousand ▁ " ) ; out += numToWords ( ( ( n / 100 ) % 10 ) , " hundred ▁ " ) ; if ( n > 100 && n % 100 ) out += " and ▁ " ; out += numToWords ( ( n % 100 ) , " " ) ; return out ; } void sortArr ( int arr [ ] , int n ) { vector < pair < string , int > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( convertToWords ( arr [ i ] ) , arr [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second << " ▁ " ; } int main ( ) { int arr [ ] = { 12 , 10 , 102 , 31 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; }