Sort the string as per ASCII values of the characters - GeeksforGeeks

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: 7GeeksExplanation: 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++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to sort the string based// on their ASCII valuesvoid 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 Codeint main(){    string S = "GeeksForGeeks";    sortString(S);     return 0;}
// java program for the above approachimport java.util.*; class Main{ // Function to sort the string based// on their ASCII valuesstatic 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 Codepublic static void main(String [] args){    String S = "GeeksForGeeks";    sortString(S);}} // This code is contributed by amreshkumar3.
# Python Program to implement# the above approach # Function to sort the string based# on their ASCII valuesdef 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 CodeS = "GeeksForGeeks"sortString(S) # This code is contributed by gfgking.
// C# implementation for the above approachusing System;class GFG{ // Function to sort the string based// on their ASCII valuesstatic 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.
<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>
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++
Python3
// 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 valuebool cmp(char ch, char chh) { return int(ch) <= int(chh); } // Function to sort the string based// on their ASCII valuesstring sortString(string S){    // Sort the string S    sort(S.begin(), S.end(), cmp);     return S;} // Driver Codeint main(){    string S = "GeeksForGeeks";    cout << sortString(S);     return 0;}
S = "GeeksForGeeks" #Sorted is a in-built pyhton function to sort and#using join we can create the new sorted stringstring = ''.join(sorted(S))  print(string) # This code is contributed by Susobhan Akhuli
FGGeeeekkorss
 Time Complexity: O(N*log N)Auxiliary Space: O(1)
lokeshpotta20
gfgking
amreshkumar3
sanjoy_62
code_hunt
susobhanakhuli
ASCII
school-programming
strings
Mathematical
Sorting
Strings
Strings
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Count all possible paths from top left to bottom right of a mXn matrix
Modular multiplicative inverse
Fizz Buzz Implementation