Skip to content
Related Articles

Related Articles

Improve Article

Sort an array of strings in increasing order of sum of ASCII values of characters

  • Difficulty Level : Expert
  • Last Updated : 29 Jun, 2021

Given an array arr[] consisting of N strings, the task is to sort the strings in increasing order of the sum of ASCII value of their characters.

Examples:

Input: arr[] = {“for”, “geeks”, “app”, “best”}
Output: app for best geeks
Explanation:
Sum of ASCII values of characters of each string is: {327, 527, 321, 430}.
Hence, the sorted order of strings is {“app”, “for”, “best”, “geeks”}.

Input: arr[] = {“geeksforgeeks”, “a”, “computer”, “science”, “portal”, “for”, “geeks”}
Output: a for geeks portal science computer geeksforgeeks
Explanation:
Sum of ASCII values of characters of each string is: {1381, 97, 879, 730, 658, 327, 527}.
Hence, the sorted order is {“a”, “for”, “geeks”, “portal”, “science”, “computer”, “geeksforgeeks”}.

 

Approach: The idea is to use an auxiliary array to store pairs of strings and their respective sum of ASCII values of characters. Then, sort the array on the basis of the first value in the pair, and then print the sorted strings. Follow the steps below to solve the problem:



Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the sum of ASCII
// value of all characters of a string
int getValue(string s)
{
    // Store the required result
    int sum = 0;
 
    // Traverse the string
    for (int i = 0; i < s.size(); i++) {
        sum += s[i];
    }
 
    // Return the sum
    return sum;
}
 
// Function to sort strings in increasing
// order of sum of their ASCII values
void sortStrings(string arr[], int n)
{
 
    // Store pairs of strings and
    // sum of their ASCII values
    vector<pair<int, string> > v;
 
    // Traverse the array, arr[]
    for (int i = 0; i < n; i++) {
 
        // Find the value of the string
        int val = getValue(arr[i]);
 
        // Append pair {val, arr[i]}
        v.push_back({ val, arr[i] });
    }
 
    // Sort the vector, V in increasing
    // order of the first value of pair
    sort(v.begin(), v.end());
 
    // Print the sorted strings
    for (int i = 0; i < n; i++) {
        cout << v[i].second << " ";
    }
}
 
// Driver Code
int main()
{
 
    // Given Input
    string arr[] = { "geeks", "for", "app", "best" };
    int n = 4;
 
    // Function Call
    sortStrings(arr, n);
 
    return 0;
}

Python3




# Python3 program for the above approach
 
# Function to find the sum of ASCII
# value of all characters of a string
def getValue(s):
     
    # Store the required result
    sum = 0
 
    # Traverse the string
    for i in range(len(s)):
        sum += ord(s[i])
 
    # Return the sum
    return sum
 
# Function to sort strings in increasing
# order of sum of their ASCII values
def sortStrings(arr, n):
 
    # Store pairs of strings and
    # sum of their ASCII values
    v = []
 
    # Traverse the array, arr[]
    for i in range(n):
         
        # Find the value of the string
        val = getValue(arr[i])
 
        # Append pair {val, arr[i]}
        v.append([val, arr[i]])
 
    # Sort the vector, V in increasing
    # order of the first value of pair
    v = sorted(v)
 
    # Print the sorted strings
    for i in range(n):
        print(v[i][1], end = " ")
 
# Driver Code
if __name__ == '__main__':
 
    # Given Input
    arr = [ "geeks", "for", "app", "best" ]
    n = 4
 
    # Function Call
    sortStrings(arr, n)
 
# This code is contributed by mohit kumar 29

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find the sum of ASCII
// value of all characters of a string
static int getValue(String s)
{
     
    // Store the required result
    int sum = 0;
 
    // Traverse the string
    for(int i = 0; i < s.Length; i++)
    {
        sum += s[i];
    }
 
    // Return the sum
    return sum;
}
 
// Function to sort strings in increasing
// order of sum of their ASCII values
static void sortStrings(String[] arr, int n)
{
 
    // Store pairs of strings and
    // sum of their ASCII values
    List<Tuple<int,
               String>> v = new List<Tuple<int,
                                           String>>();
 
    // Traverse the array, arr[]
    for(int i = 0; i < n; i++)
    {
         
        // Find the value of the string
        int val = getValue(arr[i]);
 
        // Append pair {val, arr[i]}
        v.Add(new Tuple<int, String>(val, arr[i]));
    }
 
    // Sort the vector, V in increasing
    // order of the first value of pair
    v.Sort();
 
    // Print the sorted strings
    for(int i = 0; i < n; i++)
    {
        Console.Write(v[i].Item2 + " ");
    }
}
 
// Driver Code
static public void Main()
{
     
    // Given Input
    String[] arr = { "geeks", "for", "app", "best" };
    int n = 4;
 
    // Function Call
    sortStrings(arr, n);
}
}
 
// This code is contributed by Dharanendra L V.

Javascript




<script>
 
// JavaScript program for the above approach
 
 
// Function to find the sum of ASCII
// value of all characters of a string
function getValue(s)
{
    // Store the required result
    let sum = 0;
 
    // Traverse the string
    for (let i = 0; i < s.length; i++) {
        sum += s[i].charCodeAt(0);
    }
 
    // Return the sum
    return sum;
}
 
// Function to sort strings in increasing
// order of sum of their ASCII values
function sortStrings(arr, n)
{
 
    // Store pairs of strings and
    // sum of their ASCII values
    let v = [];
 
    // Traverse the array, arr[]
    for (let i = 0; i < n; i++) {
 
        // Find the value of the string
        let val = getValue(arr[i]);
 
        // Append pair {val, arr[i]}
        v.push([ val, arr[i] ]);
    }
 
    // Sort the vector, V in increasing
    // order of the first value of pair
    v.sort();
 
    // Print the sorted strings
    for (let i = 0; i < n; i++) {
        document.write(v[i][1] + " ");
    }
}
 
// Driver Code
 
    // Given Input
    let arr = ["geeks", "for", "app", "best" ];
    let n = 4;
 
    // Function Call
    sortStrings(arr, n);
     
</script>
Output: 
app for best geeks

 

Time Complexity: O(N*log(N) + N*M), where M is the length of the longest string in the array arr[].
Auxiliary Space: O(N)

 

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :