Sort the string based on the Frequency of its characters

Write a function that gets a string as input and sorts the characters of the string by the increasing order of frequency(i.e., number of times it occurs) of its characters.



For Example:

If the string is "aaabbc", 
c has frequency of 1
b has frequency of 2
a has frequency of 3
so, the output string should be "cbbaaa"

Method 1: (Hashing)


1. Create a hash table and initialize it to '0'    
2. Parse the string and update the hash table & update the maximum count so far
3. Now, use two for loops to select count as 1,2,3,4.. max(maximum count) & another for hash table (0 to 26)
4. If the hashtable count matches the count, print the character for number of 'count' times using another for loop

Implementation:

#include <iostream>
#include<cstring>
#define MAX 100000 //Maximum size of character array

using namespace std;

//Function to return maximum value among two values
int getmax(int a,int b)
{
  return a>b?a:b;
} 

int main()
{
    char str[MAX];
    int T,hash[26];
    cin>>T; //Number of Test cases
    while(T--)
    {
      int max=0;
      cin>>str; //Input string

        //Creating a hash table and initializing it to '0' for each test case
      for(int i=0;i<26;i++)
       hash[i]=0;
        
      for(int i=0;i<strlen(str);i++)
      {
        hash[str[i]-'a']++; //update the frequency of characters
        max=getmax(max,hash[str[i]-'a']);//set max with maximum count so far
      }
     
      for(int j=1;j<=max;j++) //To check from 1 to max count
      {
        for(int i=0;i<26;i++) //To handle hash table values
        {
          if(hash[i]==j) /*If hash table value equals count, print the corresponding character count number of times.*/
          {
           char ch=i+'a';
           for(int k=0;k<j;k++)
            cout<<ch;
          }
        }
      }
      cout<<"\n";
    }
    return 0;
}