Skip to content
Related Articles

Related Articles

Sort an Array alphabetically when each number is converted into words
  • Last Updated : 26 Nov, 2020

Given an array arr[] containing N non-negative integers, the task is to sort these integers alphabetically when each number is converted into words.

Examples:  

Input: arr[] = {12, 10, 102, 31, 15} 
Output: 15 102 10 31 12 
Explanation: 
The above set of numbers are sorted alphabetically. That is: 
15 -> Fifteen 
102 -> One hundred and two 
10 -> Ten 
31 -> Thirty-one 
12 -> Twelve

Input: arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } 
Output: 8 5 4 9 1 7 6 10 3 2 
Explanation: 
The above set of numbers are sorted alphabetically. That is: 
8 -> eight 
5 -> five 
4 -> four 
9 -> nine 
1 -> one 
7 -> seven 
6 -> six 
10 -> ten 
3 -> three 
2 -> two  

Approach: In order to sort the numbers alphabetically, we first need to convert the number to its word form. Therefore, the idea is to store each element along with its word form in a vector pair and then sort all the elements of the vector according to the corresponding words of the number. Therefore: 



  • Precompute and store the word forms of all the units digits in an array.
  • Precompute and store the word forms of all the tens digits in another array.
  • For all the remaining numbers greater than 2 digits, the number is divided and the word form is added.
  • Iterate through every digit of the number in the array arr[] and store the corresponding word form of the numbers in a vector as a pair.
  • Iterate through the vector and sort the vector according to the words.
  • Finally, print the sorted order.

Below is the implementation of the above approach: 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to sort an array of
# integers alphabetically
 
# Variable to store the word form of
# units digit and up to twenty
one = [ "", "one ", "two ", "three ",
        "four ", "five ", "six ",
        "seven ", "eight ", "nine ", "ten ",
        "eleven ", "twelve ", "thirteen ",
        "fourteen ", "fifteen ", "sixteen ",
        "seventeen ", "eighteen ", "nineteen " ]
 
# Variable to store the word form of
# tens digit
ten = [ "", "", "twenty ",
        "thirty ", "forty ",
        "fifty ", "sixty ",
        "seventy ", "eighty ",
        "ninety " ]
 
# Function to convert a two digit number
# to the word by using the above defined arrays
def numToWords(n, s):
 
    st = ""
 
    # If n is more than 19, divide it
    if (n > 19):
        st += ten[n // 10] + one[n % 10]
    else:
        st += one[n]
 
    # If n is non-zero
    if (n):
        st += s
 
    return st
 
# Function to print a given number in words
def convertToWords(n):
 
    # Stores the word representation
    # of the given number n
    out = ""
 
    # Handles digits at ten millions
    # and hundred millions places
    out += numToWords((n // 10000000),
                      "crore ")
 
    # Handles digits at hundred thousands
    # and one millions places
    out += numToWords(((n // 100000) % 100),
                      "lakh ")
 
    # Handles digits at thousands and
    # tens thousands places
    out += numToWords(((n // 1000) % 100),
                      "thousand ")
 
    # Handles digit at hundreds places
    out += numToWords(((n // 100) % 10),
                      "hundred ")
 
    if (n > 100 and n % 100):
        out += "and "
 
    # Call the above function to convert
    # the number into words
    out += numToWords((n % 100), "")
 
    return out
 
# Function to sort the array according to
# the albhabetical order
def sortArr(arr, n):
 
    # Vector to store the number in words
    # with respective elements
    vp = []
 
    # Inserting number in words
    # with respective elements in vector pair
    for i in range(n):
        vp.append((convertToWords(arr[i]),
                                  arr[i]));
    
    # Sort the vector, this will sort the pair
    # according to the alphabetical order.
    vp.sort()
 
    # Print the sorted vector content
    for i in range(len(vp)):
        print (vp[i][1], end = " ")
 
# Driver code
if __name__ == "__main__":
   
    arr = [ 12, 10, 102, 31, 15 ]
    n = len(arr)
 
    sortArr(arr, n)
 
# This code is contributed by chitranayal

chevron_right


Output: 

15 102 10 31 12

 

Time Complexity: O(N * log(N)), where N is the size of the array
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :