Sort string of characters

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to sort a string of characters 
  
import java.util.Arrays;
  
class GFG {
  
// function to print string in sorted order 
    static void sortString(String str) {
        char []arr = str.toCharArray();
        Arrays.sort(arr);
        System.out.print(String.valueOf(arr));
    }
  
// Driver program to test above function 
    public static void main(String[] args) {
        String s = "geeksforgeeks";
        sortString(s);
    }
}
// This code is contributed by Rajput-Ji 

chevron_right


Python3

# Python3 program to sort a string
# of characters

# function to print string in
# sorted order
def sortString(str) :
str = ”.join(sorted(str))
print(str)

# Driver Code
s = “geeksforgeeks”
sortString(s)

# This code is contributed by Smitha

C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to sort a string of characters 
using System;    
public class GFG { 
  
// function to print string in sorted order 
    static void sortString(String str) { 
        char []arr = str.ToCharArray(); 
        Array.Sort(arr); 
        Console.WriteLine(String.Join("",arr)); 
    
  
// Driver program to test above function 
    public static void Main() { 
        String s = "geeksforgeeks"
        sortString(s); 
    
// This code is contributed by 29AjayKumar

chevron_right


Output:

eeeefggkkorss

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

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 = "geeksforgeeks";    
    sortString(s);    
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to sort 
// a string of characters
import java.util.Arrays;
import java.util.Collections;
  
class GFG 
{
    // Method to sort a 
    // string alphabetically
    public static String sortString(String inputString)
    {
        // convert input 
        // string to char array
        char tempArray[] = 
             inputString.toCharArray();
          
        // sort tempArray
        Arrays.sort(tempArray);
          
        // return new sorted string
        return new String(tempArray);
    }
      
    // Driver Code
    public static void main(String[] args)
    {
        String inputString = "geeksforgeeks";
          
        System.out.println(sortString(inputString));
    }
}
  
// This code is contributed 
// by prabhat kumar singh

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to sort a string 
# of characters
  
MAX_CHAR = 26
  
# function to print string in sorted order
def sortString(str):
      
    # Hash array to keep count of characters.
    # Initially count of all charters is 
    # initialized to zero.
    charCount = [0 for i in range(MAX_CHAR)]
      
    # Traverse string and increment 
    # count of characters
    for i in range(0, len(str), 1):
          
        # '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[ord(str[i]) - ord('a')] += 1
      
    # Traverse the hash array and print 
    # characters
    for i in range(0, MAX_CHAR, 1):
        for j in range(0, charCount[i], 1):
            print(chr(ord('a') + i), end = "")
  
# Driver Code
if __name__ == '__main__':
    s = "geeksforgeeks"
    sortString(s)
      
# This code is contributed by
# Sahil_Shelangia

chevron_right


.

C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to sort 
// a string of characters 
using System;
  
class GFG
{
      
    // Method to sort a 
    // string alphabetically 
    public static string sortString(string inputString)
    {
          
        // convert input 
        // string to char array 
        char[] tempArray = inputString.ToCharArray();
  
        // sort tempArray 
        Array.Sort(tempArray);
  
        // return new sorted string 
        return new string(tempArray);
    }
  
    // Driver Code 
    public static void Main(string[] args)
    {
        string inputString = "geeksforgeeks";
  
        Console.WriteLine(sortString(inputString));
    }
}
  
// This code is contributed by Shrikant13

chevron_right



Output:

eeeefggkkorss

Time Complexity: O( n ), where n is the length of input string.
Auxiliary Space: O( 1 ).

This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.