Skip to content
Related Articles
Open in App
Not now

Related Articles

C++ Program To Sort String of Characters

Improve Article
Save Article
Like Article
  • Last Updated : 02 Mar, 2023
Improve Article
Save Article
Like Article

Given a string of lowercase characters from ‘a’ – ‘z’. We need to write a program to print the characters of this string in sorted order.
Examples:

Input: bbccdefbbaa 
Output: aabbbbccdef

Input: geeksforgeeks
Output: eeeefggkkorss

A simple approach will be to use sorting algorithms like quick sort or merge sort and sort the input string and print it. 

C++




// C++ program to sort a
// string of characters
#include<bits/stdc++.h>
using namespace std;
 
// Function to print string
// in sorted order
void sortString(string &str)
{
   sort(str.begin(), str.end());
   cout << str;
}
 
// Driver code
int main()
{
    string s = "geeksforgeeks";
    sortString(s);
    return 0;
}


Output:  

eeeefggkkorss

Time Complexity: O(n log n), where n is the length of string.

Space Complexity: O(1) as no extra space has been used.

An efficient approach will be to observe first that there can be a total of 26 unique characters only. So, we can store the count of occurrences of all the characters from ‘a’ to ‘z’ in a hashed array. The first index of the hashed array will represent character ‘a’, second will represent ‘b’ and so on. Finally, we will simply traverse the hashed array and print the characters from ‘a’ to ‘z’ the number of times they occurred in input string.
Below is the implementation of above idea: 

C++




// C++ program to sort a
// string of characters
#include<bits/stdc++.h>
using namespace std;
 
const int MAX_CHAR = 26;
 
// Function to print string
// in sorted order
void sortString(string &str)
{
    // Hash array to keep count of characters.
    // Initially count of all characters is
    // initialized to zero.
    int charCount[MAX_CHAR] = {0};
     
    // Traverse string and increment
    // count of characters
    for (int i=0; i<str.length(); i++)
 
        // 'a'-'a' will be 0, 'b'-'a' will be 1,
        // so for location of character in count
        // array we will do str[i]-'a'.
        charCount[str[i]-'a']++;   
     
    // Traverse the hash array and print
    // characters
    for (int i=0;i<MAX_CHAR;i++)
        for (int j=0;j<charCount[i];j++)
            cout << (char)('a'+i);
}
 
// Driver code
int main()
{
    string s = "geeksforgeeks";   
    sortString(s);   
    return 0;
}


Output:  

eeeefggkkorss

Time Complexity: O(Max_CHAR*n) which becomes O(n) as MAX_CHAR is  constant,So Overall Time Complexity:- O(n) where n is the length of the string.  
Auxiliary Space: O( 1 )


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!