Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Searching For Characters and Substring in a String in Java
Next article icon

Sort the given string using character search

Last Updated : 04 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Implementation:

C++
// 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 technique 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 program to test above int main() {   string str = "geeksforgeeks";   int n = str.size();   cout << sortString(str, n);   return 0; } 
Java
// Java implementation to sort the given  // string without using any sorting technique 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.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
# Python3 implementation to sort  # the given string without using # any sorting technique  # Function to sort the given string  # without using any sorting technique def 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 Code str = "geeksforgeeks" n = len(str) print(sortString(str, n))  # This code is contributed by Anant Agarwal. 
C#
// C# implementation to sort the given // string without using any sorting technique using 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 
JavaScript
<script>  // Javascript implementation to sort the given string without // using any sorting technique  // function to sort the given string without // using any sorting technique function 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 above var str = "geeksforgeeks"; var n = str.length; document.write( sortString(str, n));  </script>  

Output : 
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++
// 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 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]--)     new_str += i+'a';   return new_str;  }   // Driver program to test above  int main() {  string str = "geeksforgeeks";  int n = str.size();  cout << sortString(str, n);  return 0;  }   // This code is contributed by Aravind Alapati 
Java
// Java implementation to sort the given // String without using any sorting technique 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 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 
Python3
# Python 3 implementation to sort the given # string without using any sorting technique def 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 above if __name__ == "__main__":      st = "geeksforgeeks"     n = len(st)     print(sortString(st, n))      # This code is contributed by ukasp. 
C#
// C# implementation to sort the given // String without using any sorting technique using 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 
JavaScript
<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 string  var new_str = "";   //To store each occurrence of character by relative indexing for (i = 0; i < n; i++)     ++arr[str[i].charCodeAt(0) -'a'.charCodeAt(0)];   //To traverse the character array and append it to new_str for(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>   

Output : 
eeeefggkkorss

 

Time complexity : O(n) 
Auxiliary Space : O(1)


Next Article
Searching For Characters and Substring in a String in Java

A

ayushjauhari14
Improve
Article Tags :
  • Strings
  • Searching
  • Sorting
  • DSA
Practice Tags :
  • Searching
  • Sorting
  • Strings

Similar Reads

  • Sort the string as per ASCII values of the characters
    Given a string S of size N, the task is to sort the string based on its ASCII values. Examples: Input: S = "Geeks7"Output: 7GeeksExplanation: According to the ASCII values, integers comes first, then capital alphabets and the small alphabets. Input: S = "GeeksForGeeks"Output: FGGeeeekkorss Approach:
    6 min read
  • Program to Search a Character in a String
    Given a character ch and a string s, the task is to find the index of the first occurrence of the character in the string. If the character is not present in the string, return -1. Examples: Input: s = "geeksforgeeks", ch = 'k'Output: 3Explanation: The character 'k' is present at index 3 and 11 in "
    6 min read
  • 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 : "dcab" Output : "abcd"Input : "geeksforgeeks"Output : "eeeefggkkorss" Naive Approach - O(n Log n) TimeA simple approach is to use sorting algori
    5 min read
  • Find uncommon characters of the two strings
    Given two strings s1 and s2, the task is to find the uncommon characters in both strings. An uncommon character means that the character is present in only one string or in another string but not in both. The strings contain only lowercase characters and can have duplicates. Note: Output the uncommo
    13 min read
  • Searching For Characters and Substring in a String in Java
    Efficient String manipulation is very important in Java programming especially when working with text-based data. In this article, we will explore essential methods like indexOf(), contains(), and startsWith() to search characters and substrings within strings in Java. Searching for a Character in a
    5 min read
  • Find the Nth occurrence of a character in the given String
    Given string str, a character ch, and a value N, the task is to find the index of the Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists. Examples: Input: str = "Geeks", ch = 'e', N = 2 Output: 2 Input: str = "GFG", ch = 'e', N = 2 Output: -1 Recommended
    7 min read
  • Python | Check order of character in string using OrderedDict( )
    Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern. Examples: Input: string = "engineers rock"pattern = "er";Output: trueExplanation: All
    3 min read
  • Sort a string according to the frequency of characters
    Given a string str, the task is to sort the string according to the frequency of each character, in ascending order. If two elements have the same frequency, then they are sorted in lexicographical order.Examples: Input: str = "geeksforgeeks" Output: forggkksseeee Explanation: Frequency of character
    15 min read
  • Find the Suffix Array of given String with no repeating character
    Given a string str of size N, the task is to find the suffix array of the given string. Note: A suffix array is a sorted array of all suffixes of a given string. Examples: Input: str = "prince"Output: 4 5 2 3 0 1Explanation: The suffixes are0 prince 4 ce1 rince Sort the suffixes 5 e 2 ince ---------
    6 min read
  • Check if a two character string can be made using given words
    Given a string of two characters and n distinct words of two characters. The task is to find if it is possible to arrange given words in such a way that the concatenated string has the given two character string as a substring. We can append a word multiple times. Examples: Input : str = "ya" words[
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences