Open In App

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

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N strings, the task is to sort the strings in increasing order of the sum of the ASCII (American Standard Code for Information Interchange) 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;
}


Java




/*package whatever //do not write package name here */
import java.util.*;
class pair
{
   
  // Instead of pair in cpp
  // I have created a java class
  int first;
  String second;
  pair(int first,String second)
  {
    this.first = first;
    this.second = second;
  }
}
class Gfg
{
 
  // Function to find the sum of ASCII
  // value of all characters of a string
  public static int getValue(String s)
  {
    int sum = 0;
     
    // Traverse the String
    for (int i = 0; i < s.length(); i++) {
      sum += s.charAt(i);
    }
 
    // Return the sum
    return sum;
  }
   
  // Function to sort strings in increasing
  // order of sum of their ASCII values
  public static void sortStrings(String arr[],int n)
  {
     
    // Store pairs of strings and
    // sum of their ASCII values
    ArrayList<pair> v = new ArrayList<pair>();
     
    // 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 pair(val,arr[i]));
    }
     
    // Sort the vector, V in increasing
    // order of the first value of pair
    Collections.sort(v,(a,b)->a.first-b.first);
    for (int i = 0; i < n; i++) {
      System.out.print(v.get(i).second+" ");
    }
  }
  public static void main(String[] args) {
    String arr[] = {"geeks","for","app","best"};
    int n = 4;
    sortStrings(arr,n);
 
  }
}
 
// This code is contributed by anskalyan3.


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)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads