Skip to content
Related Articles

Related Articles

Sort the string as per ASCII values of the characters

Improve Article
Save Article
Like Article
  • Last Updated : 26 Apr, 2022

Given a string S of size N, the task is to sort the string based on their ASCII values.

Examples:

Input: S = “Geeks7”
Output: 7Geeks
Explanation: According to the ASCII values, integers comes first, then capital alphabets and the small alphabets.

Input: S = “GeeksForGeeks”
Output: FGGeeeekkorss

Approach: The idea to solve this problem is to maintain an array to store the frequency of each character and then add them accordingly in the resultant string. Since there are at max 256 characters which make the space complexity constant. Follow the steps below to solve this problem:

  • Initialize a vector freq[] of size 256 with values 0 to store the frequency of each character of the string.
  • Iterate over the range [0, N) using the variable i and increase the count of s[i] in the array freq[] by 1.
  • Make the string S as an empty string.
  • Iterate over the range [0, N) using the variable i and iterate over the range [0, freq[i]) using the variable j and adding the character corresponding to the i-th ASCII value in the string s[].
  • After performing the above steps, print the string S as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort the string based
// on their ASCII values
void sortString(string s)
{
    int N = s.length();
 
    // Stores the frequency of each
    // character of the string
    vector<int> freq(256, 0);
 
    // Count and store the frequency
    for (int i = 0; i < N; i++) {
        freq[s[i]]++;
    }
 
    s = "";
 
    // Store the result
    for (int i = 0; i < 256; i++) {
        for (int j = 0; j < freq[i]; j++)
            s = s + (char)i;
    }
 
    // Print the result
    cout << s << "\n";
 
    return;
}
 
// Driver Code
int main()
{
    string S = "GeeksForGeeks";
    sortString(S);
 
    return 0;
}


Java




// java program for the above approach
import java.util.*;
 
class Main
{
 
// Function to sort the string based
// on their ASCII values
static void sortString(String s)
{
    int N = s.length();
 
    // Stores the frequency of each
    // character of the string
    int [] freq = new int [256];
    for(int i = 0; i < 256; i++){
        freq[i] = 0;
    }
 
    // Count and store the frequency
    for (int i = 0; i < N; i++) {
         char character = s.charAt(i);
         int val = (int) character;
        freq[val]++;
    }
 
    // Store the result
    for (int i = 0; i < 256; i++) {
        for (int j = 0; j < freq[i]; j++)
          //    s = s + (char)i;
            System.out.print((char)i);
    }
}
 
// Driver Code
public static void main(String [] args)
{
    String S = "GeeksForGeeks";
    sortString(S);
}
}
 
// This code is contributed by amreshkumar3.


Python3




# Python Program to implement
# the above approach
 
# Function to sort the string based
# on their ASCII values
def sortString(s):
    N = len(s)
 
    # Stores the frequency of each
    # character of the string
    freq = [0] * 256
 
    # Count and store the frequency
    for i in range(0, N) :
        freq[ord(s[i])] += 1
 
    s = ""
 
    # Store the result
    for i in range(256):
        for j in range(freq[i]):
            s = s + chr(i)
 
    # Print the result
    print(s)
 
    return
 
# Driver Code
S = "GeeksForGeeks"
sortString(S)
 
# This code is contributed by gfgking.


C#




// C# implementation for the above approach
using System;
class GFG
{
 
// Function to sort the string based
// on their ASCII values
static void sortString(string s)
{
    int N = s.Length;
 
    // Stores the frequency of each
    // character of the string
    int [] freq = new int[256];
    for(int i = 0; i < 256; i++){
        freq[i] = 0;
    }
 
    // Count and store the frequency
    for (int i = 0; i < N; i++) {
         char character = s[i];
         int val = (int) character;
        freq[val]++;
    }
 
    // Store the result
    for (int i = 0; i < 256; i++) {
        for (int j = 0; j < freq[i]; j++)
          //    s = s + (char)i;
           Console.Write((char)i);
    }
}
 
    // Driver Code
    public static void Main()
    {
        string S = "GeeksForGeeks";
        sortString(S);
    }
}
 
// This code is contributed by sanjoy_62.


Javascript




<script>
       // JavaScript Program to implement
       // the above approach
 
       // Function to sort the string based
       // on their ASCII values
       function sortString(s)
       {
           let N = s.length;
 
           // Stores the frequency of each
           // character of the string
           let freq = new Array(256).fill(0)
 
           // Count and store the frequency
           for (let i = 0; i < N; i++) {
               freq[s[i].charCodeAt(0)]++;
           }
 
           s = "";
 
           // Store the result
           for (let i = 0; i < 256; i++) {
               for (let j = 0; j < freq[i]; j++)
                   s = s + String.fromCharCode(i);
           }
 
           // Print the result
           document.write(s);
 
           return;
       }
 
       // Driver Code
       let S = "GeeksForGeeks";
       sortString(S);
 
       // This code is contributed by Potta Lokesh
 
   </script>


Output

FGGeeeekkorss

 Time Complexity: O(256*N)
Auxiliary Space: O(256)

Alternate Approach: The given problem can also be solved by using the comparator function with the inbuilt sort() function to sort the given string as per their ASCII values.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;
 
// Comparator Function to sort the given
// string in increasing order of their
// ASCII value
bool cmp(char ch, char chh) { return int(ch) <= int(chh); }
 
// Function to sort the string based
// on their ASCII values
string sortString(string S)
{
    // Sort the string S
    sort(S.begin(), S.end(), cmp);
 
    return S;
}
 
// Driver Code
int main()
{
    string S = "GeeksForGeeks";
    cout << sortString(S);
 
    return 0;
}


Python3




S = "GeeksForGeeks"
 
#Sorted is a in-built pyhton function to sort and
#using join we can create the new sorted string
string = ''.join(sorted(S))  
print(string)
 
# This code is contributed by Susobhan Akhuli


Output

FGGeeeekkorss

 Time Complexity: O(N*log N)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!