Sort the given string using character search

16 Jun, 2022
Given a string str of size n. The problem is to sort the given string without using any sorting techniques (like bubble, selection, etc). The string contains only lowercase characters.Examples:  
Input : geeksforgeeks
Output : eeeefggkkorss

Input : coding
Output : cdgino
 
Algorithm:  
sortString(str, n)
    Initialize new_str = ""
    
    for i = 'a' to 'z'
        for j = 0 to n-1
            if str[j] == i, then
                new_str += str[j]

    return new_str
 
C++
Java
Python3
C#
Javascript
// C++ implementation to sort the given string without// using any sorting technique#include <bits/stdc++.h>using namespace std; // function to sort the given string without// using any sorting techniquestring sortString(string str, int n) {   // to store the final sorted string  string new_str = "";   // for each character 'i'  for (int i = 'a'; i <= 'z'; i++)     // if character 'i' is present at a particular    // index then add character 'i' to 'new_str'    for (int j = 0; j < n; j++)      if (str[j] == i)        new_str += str[j];   // required final sorted string  return new_str;} // Driver program to test aboveint main() {  string str = "geeksforgeeks";  int n = str.size();  cout << sortString(str, n);  return 0;}
// Java implementation to sort the given// string without using any sorting techniqueclass GFG {         // function to sort the given string    // without using any sorting technique    static String sortString(String str, int n)    {         // to store the final sorted string        String new_str = "";         // for each character 'i'        for (int i = 'a'; i <= 'z'; i++)             // if character 'i' is present at a            // particular index then add character            // 'i' to 'new_str'            for (int j = 0; j < n; j++)                if (str.charAt(j) == i)                    new_str += str.charAt(j);         // required final sorted string        return new_str;    }         // Driver code    public static void main(String[] args)    {        String str = "geeksforgeeks";        int n = str.length();                 System.out.print(sortString(str, n));    }} // This code is contributed by Anant Agarwal.
# Python3 implementation to sort# the given string without using# any sorting technique # Function to sort the given string# without using any sorting techniquedef sortString(str, n):     # To store the final sorted string    new_str = ""     # for each character 'i'    for i in range(ord('a'), ord('z') + 1):         # if character 'i' is present at a particular        # index then add character 'i' to 'new_str'        for j in range(n):            if (str[j] == chr(i)):                new_str += str[j]     # required final sorted string    return new_str # Driver Codestr = "geeksforgeeks"n = len(str)print(sortString(str, n)) # This code is contributed by Anant Agarwal.
// C# implementation to sort the given// string without using any sorting techniqueusing System; class GFG {         // function to sort the given string    // without using any sorting technique    static String sortString(String str, int n)    {        // to store the final sorted string        String new_str = "";         // for each character 'i'        for (int i = 'a'; i <= 'z'; i++)             // if character 'i' is present at a            // particular index then add character            // 'i' to 'new_str'            for (int j = 0; j < n; j++)                if (str[j] == i)                    new_str += str[j];         // required final sorted string        return new_str;    }     // Driver code    public static void Main()    {        String str = "geeksforgeeks";        int n = str.Length;         Console.Write(sortString(str, n));    }} // This code is contributed by Sam007
<script> // Javascript implementation to sort the given string without// using any sorting technique // function to sort the given string without// using any sorting techniquefunction sortString(str, n) {   // to store the final sorted string  var new_str = "";   // for each character 'i'  for (var i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++)     // if character 'i' is present at a particular    // index then add character 'i' to 'new_str'    for (var j = 0; j < n; j++)      if (str[j].charCodeAt(0) == i)        new_str += str[j];   // required final sorted string  return new_str;} // Driver program to test abovevar str = "geeksforgeeks";var n = str.length;document.write( sortString(str, n)); </script>
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
eeeefggkkorss
 
Time complexity : O(n) Auxiliary Space : O(1)
Method 2: In the above method we have to traverse the entire string every time for each of the character in set of ‘a’ to ‘z’.We can overcome this drawback by maintaining a character and filling it with number of the occurrence’s of all the characters in the string.Later we can construct the required sorted string from the character array.Below is the implementation.  
C++
Java
Python3
C#
Javascript
// C++ implementation to sort the given// string without using any sorting technique#include <iostream>using namespace std; string sortString(string str, int n) {int i;//A character array to store the no.of occurrences of each character//between 'a' to 'z'char arr[26]={0}; //to store the final sorted stringstring new_str = ""; //To store each occurrence of character by relative indexingfor (i = 0; i < n; i++)   ++arr[str[i]-'a'];  //To traverse the character array and append it to new_strfor(i=0;i<26;i++)  while(arr[i]--)    new_str += i+'a'; return new_str;} // Driver program to test aboveint main() {string str = "geeksforgeeks";int n = str.size();cout << sortString(str, n);return 0;} // This code is contributed by Aravind Alapati
// Java implementation to sort the given// String without using any sorting techniqueclass GFG{     static String sortString(String str, int n)    {        int i;                 // A character array to store        // the no.of occurrences of each        // character between 'a' to 'z'        char[] arr = new char[26];         // to store the final sorted String        String new_str = "";         // To store each occurrence of        // character by relative indexing        for (i = 0; i < n; i++)            ++arr[str.charAt(i) - 'a'];         // To traverse the character        // array and append it to new_str        for (i = 0; i < 26; i++)            while (arr[i]-- > 0)            {                new_str += String.valueOf((char)(i + 'a'));            }         return new_str;    }     // Driver code    public static void main(String[] args)    {        String str = "geeksforgeeks";        int n = str.length();        System.out.print(sortString(str, n));    }} // This code is contributed by Rajput-Ji
# Python 3 implementation to sort the given# string without using any sorting techniquedef sortString(st, n):       # A character array to store the no.of occurrences of each character    # between 'a' to 'z'    arr = [0] * 26     # to store the final sorted string    new_str = ""         # To store each occurrence of character by relative indexing    for i in range(n):        arr[ord(st[i]) - ord('a')] += 1     # To traverse the character array and append it to new_str    for i in range(26):        while(arr[i] > 0):            new_str += chr(i+ord('a'))            arr[i] -= 1     return new_str # Driver program to test aboveif __name__ == "__main__":     st = "geeksforgeeks"    n = len(st)    print(sortString(st, n))     # This code is contributed by ukasp.
// C# implementation to sort the given// String without using any sorting techniqueusing System; class GFG{     static String sortString(String str, int n)    {        int i;                 // A character array to store        // the no.of occurrences of each        // character between 'a' to 'z'        char[] arr = new char[26];         // to store the readonly sorted String        String new_str = "";         // To store each occurrence of        // character by relative indexing        for (i = 0; i < n; i++)            ++arr[str[i] - 'a'];         // To traverse the character        // array and append it to new_str        for (i = 0; i < 26; i++)            while (arr[i]-- > 0)            {                new_str += String.Join("",(char)(i + 'a'));            }         return new_str;    }     // Driver code    public static void Main(String[] args)    {        String str = "geeksforgeeks";        int n = str.Length;        Console.Write(sortString(str, n));    }} // This code is contributed by 29AjayKumar
<script> // Javascript implementation to sort the given// string without using any sorting technique function sortString(str, n) {var i;//A character array to store the no.of occurrences of each character//between 'a' to 'z'var arr = Array(26).fill(0); //to store the final sorted stringvar new_str = ""; //To store each occurrence of character by relative indexingfor (i = 0; i < n; i++)   ++arr[str[i].charCodeAt(0) -'a'.charCodeAt(0)];  //To traverse the character array and append it to new_strfor(i=0;i<26;i++)  while(arr[i]--)    new_str += String.fromCharCode(i +'a'.charCodeAt(0)); return new_str;} // Driver program to test above var str = "geeksforgeeks";var n = str.length;document.write( sortString(str, n));  </script>
eeeefggkkorss
 
Time complexity : O(n) Auxiliary Space : O(1)
Sort the given string using character search | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersSort the given string using character search | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oyhg9rZYU7s" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Aravind_Alapati
Rajput-Ji
29AjayKumar
rrrtnx
itsok
gabaa406
ukasp
a7977370173
Searching
Sorting
Strings
Searching
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.