• Register
search
Log In

Consider a string containing characters from a to z. We will be writing a program to print the characters in sorted order. To do so we can apply two methods, both methods are discussed below.

 

Methods

  • Using quick sort

Quick sort is the technique of sorting in C++. We take help of another element as a reference. I have already discussed this technique in my recent article. You can check it out for further information. The method I covered is for searching an element but it is similar for sorting, you will understand. https://kodlogs.com/blog/290/find-element-in-binary-search-tree-c

 

Program 

#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 program to test above function 
int main() 
{ 
    string s = "huuihdfv";  
    sortString(s);  
    return 0; 
} 
  • Storing in array

We will create a hashed array. Hashed array stores the count of occurrences of all characters from a to z. The hashed array ‘a’ will be represented by the first index and ‘b’ will be by the second index and so on. In the end, we will traverse the array and print the characters.

 

Program 

// 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 charters 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 wil 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 program to test above function 
int main() 
{ 
    string s = "oudhfvhdasz";     
    sortString(s);     
    return 0; 
} 

Comment if you have any issues or doubts related to C++.

posted May 30 in c++ 100 points