Open In App

C++ Program to Sort String of Characters

Last Updated : 16 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Sorting a string means rearranging the characters of the given string in some defined order such as alphabetical order. In this article, we will learn how to sort a string by characters in C++.

Examples

Input: str = “geeksforgeeks”
Output: “eeeefggkkorss”
Explanation: The characters in the string are sorted in alphabetical order.

Input: str = “programming”
Output: “aggimmnoprr”
Explanation: The characters in the string are sorted in alphabetical order.

Sort String by Characters Using Library Function

In C++, the std::sort() function from STL is a simple and efficient way to sort characters of a string. This function works for both C and C++ style strings.

Syntax of std::sort()

std::sort(first, last, comp);

where first and last are the iterator/pointer to the first and the theoretical character after the last character of the string. comp is the comparator function that defines the sorting order. By default, this function sorts the string in increasing alphabetical order.

Example

// C++ Program to sort a string of characters
// using sort() from STL
#include <bits/stdc++.h>
using namespace std;

int main() {
  
  	// C++ Style string
    string str1 = "geeksforgeeks";
  
  	// C++ Style string
  	char str2[] = "programming";
  	int len2 = strlen(str2);

    // Sort the strings using std::sort()
    sort(str1.begin(), str1.end());
  	sort(str2, str2 + len2);

    cout << str1 << endl;
  	cout << str2;
    return 0;
}

Output
eeeefggkkorss
aggimmnoprr

Time Complexity: O(n * log n), where n is the number of characters in the string.
Auxiliary Space: O(n)

Other Methods to Sort String by Characters in C++

C++ provides many different methods to sort the characters of the given string which are listed below:

Manually Using Counting Sort

We observe that there can only be a total of 26 unique characters in a string (not considering alphabets and uppercase characters). In this case, counting sort algorithm can be more efficient because it works by counting the frequency of each character and then reconstructing the sorted string by positioning them using their cumulative frequency.

// C++ Program to sort a string of characters
// using Counting Sort
#include <bits/stdc++.h>
using namespace std;

// Maximum range of ASCII lowercase alphabets
#define RANGE 26

void countSort(string &str) {
    int n = str.length();
    
    // Output array to store sorted string
    char out[n + 1];
    
    // Count array to store frequency
    int count[RANGE] = {0};

    // Store the count of each character
    for (int i = 0; i < n; i++) {
        count[str[i] - 'a']++;
    }

    // Modify count array to store cumulative
  	// position of characters
    for (int i = 1; i < RANGE; i++) {
        count[i] += count[i - 1];
    }

    // Building output array based on the 
  	// cumulative positions
    for (int i = n - 1; i >= 0; i--) {
        out[count[str[i] - 'a'] - 1] = str[i];
        count[str[i] - 'a']--;
    }
    out[n] = '\0';

    // Copy the sorted characters back to the original string
    for (int i = 0; i < n; i++) {
        str[i] = out[i];
    }
}

int main() {
    string str = "geeksforgeeks";

    // Sort the string using Counting Sort
    countSort(str);
  
    cout << str << endl;
    return 0;
}

Output
eeeefggkkorss

Time Complexity: O(k + n), where n is the number of characters in the string.
Auxiliary Space: O(k + n), where k is the number of unique characters.

Using std::multiset

We can also sort the string of characters using std::multiset container as an intermediate which automatically stores the given elements in the increasing order. We can then copy these sorted characters back to our string.

We can change the order of multiset by providing custom comparator at the time of declaration.

// C++ Program to sort a string of characters
// using std::multiset
#include <iostream>
#include <set>
#include <string>
using namespace std;

int main() {
    string str = "geeksforgeeks";

    // Create a multiset and initialize it using str
    multiset<char> m(str.begin(), str.end());
	
  	// Copy back the sorted character to the string
  	// using std::copy
    copy(m.begin(), m.end(), str.begin());
    
    cout << str;
    return 0;
}

Output
eeeefggkkorss

Time Complexity: O(n * log n), where n is the number of characters in the string.
Auxiliary Space: O(n)

We can also use std::priority_queue that implements max heap to store the elements and then pop them one by one and store them in the string in reverse.

Otherwise, we can implement the sorting algorithm of our choice to get better control.




Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg