C++ Program To Sort String of Characters
Last Updated :
11 Oct, 2023
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++
#include<bits/stdc++.h>
using namespace std;
void sortString(string &str)
{
sort(str.begin(), str.end());
cout << str;
}
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++
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
void sortString(string &str)
{
int charCount[MAX_CHAR] = {0};
for ( int i=0; i<str.length(); i++)
charCount[str[i]- 'a' ]++;
for ( int i=0;i<MAX_CHAR;i++)
for ( int j=0;j<charCount[i];j++)
cout << ( char )( 'a' +i);
}
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 )
Share your thoughts in the comments
Please Login to comment...