Sort an alphanumeric string such that the positions of alphabets and numbers remain unchanged

07 May, 2021
Given an alphanumeric string str, the task is to sort the string in such a way that if a position is occupied by an alphabet it must be occupied by an alphabet after sorting and if occupied by a number it must be occupied by a number after sorting.Examples:  
Input: str = “geeks12for32geeks” Output: eeeef12ggk23korssInput: str = “d4c3b2a1” Output: a1b2c3d4  
 
Approach: We will convert the string to a character array and then sort the character array c[]. After sorting the character array the numeric characters will occupy starting indices of the array and the alphabets will occupy the remaining part of the array. The numeric half will be sorted and the alphabet part will also be sorted. We will keep two indices one at the starting index of the alphabet part al_c and one at the starting index of numeric part nu_c, now we will check the original string and if a position was occupied by an alphabet then we will replace it with c[al_c] and increment al_c else we will replace it with c[nu_c] and increment nu_c.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns the string s// in sorted form such that the// positions of alphabets and numeric// digits remain unchangedstring sort(string s){    char c[s.length() + 1];     // String to character array    strcpy(c, s.c_str());     // Sort the array    sort(c, c + s.length());     // Count of alphabets and numbers    int al_c = 0, nu_c = 0;     // Get the index from where the    // alphabets start    while (c[al_c] < 97)        al_c++;     // Now replace the string with sorted string    for (int i = 0; i < s.length(); i++) {         // If the position was occupied by an        // alphabet then replace it with alphabet        if (s[i] < 97)            s[i] = c[nu_c++];         // Else replace it with a number        else            s[i] = c[al_c++];    }     // Return the sorted string    return s;} // Driver codeint main(){    string s = "d4c3b2a1";     cout << sort(s);     return 0;}
// A Java implementation of the approachimport java.util.*; class GFG{ // Function that returns the string s// in sorted form such that the// positions of alphabets and numeric// digits remain unchangedstatic String sort(String s){    char []c = new char[s.length() + 1];     // String to character array    c = s.toCharArray();     // Sort the array    Arrays.sort(c);     // Count of alphabets and numbers    int al_c = 0, nu_c = 0;     // Get the index from where the    // alphabets start    while (c[al_c] < 97)        al_c++;     // Now replace the string with sorted string    for (int i = 0; i < s.length(); i++)    {         // If the position was occupied by an        // alphabet then replace it with alphabet        if (s.charAt(i) < 97)            s = s.substring(0,i)+ c[nu_c++]+s.substring(i+1);         // Else replace it with a number        else            s = s.substring(0,i)+ c[al_c++]+s.substring(i+1);    }     // Return the sorted string    return s;} // Driver codepublic static void main(String[] args){    String s = "d4c3b2a1";     System.out.println(sort(s));}} /* This code contributed by PrinciRaj1992 */
# Python3 implementation of the approach # Function that returns the string s# in sorted form such that the# positions of alphabets and numeric# digits remain unchangeddef sort(s):     # String to character array    c, s = list(s), list(s)     # Sort the array    c.sort()     # Count of alphabets and numbers    al_c = 0    nu_c = 0     # Get the index from where the    # alphabets start    while ord(c[al_c]) < 97:        al_c += 1     # Now replace the string with sorted string    for i in range(len(s)):         # If the position was occupied by an        # alphabet then replace it with alphabet        if s[i] < 'a':            s[i] = c[nu_c]            nu_c += 1         # Else replace it with a number        else:            s[i] = c[al_c]            al_c += 1     # Return the sorted string    return ''.join(s) # Driver Codeif __name__ == "__main__":    s = "d4c3b2a1"    print(sort(s)) # This code is contributed by# sanjeev2552
// C# implementation of the approachusing System; class GFG{     // Function that returns the string s    // in sorted form such that the    // positions of alphabets and numeric    // digits remain unchanged    static string sort(string s)    {        char []c = new char[s.Length + 1];             // String to character array        c = s.ToCharArray();             // Sort the array        Array.Sort(c);             // Count of alphabets and numbers        int al_c = 0, nu_c = 0;             // Get the index from where the        // alphabets start        while (c[al_c] < 97)            al_c++;             // Now replace the string with sorted string        for (int i = 0; i < s.Length; i++)        {                 // If the position was occupied by an            // alphabet then replace it with alphabet            if (s[i] < 97)                s = s.Substring(0,i)+ c[nu_c++]+s.Substring(i+1);                 // Else replace it with a number            else                s = s.Substring(0,i)+ c[al_c++]+s.Substring(i+1);        }             // Return the sorted string        return s;    }         // Driver code    public static void Main()    {        string s = "d4c3b2a1";             Console.WriteLine(sort(s));    }} /* This code contributed by AnkitRai01 */
<script> // Javascript implementation of the approach // Function that returns the string s// in sorted form such that the// positions of alphabets and numeric// digits remain unchangedfunction sort(s){    var c = s.split('');     c.sort();     // Count of alphabets and numbers    var al_c = 0, nu_c = 0;     // Get the index from where the    // alphabets start    while (c[al_c].charCodeAt(0) < 97)        al_c++;     // Now replace the string with sorted string    for (var i = 0; i < s.length; i++) {         // If the position was occupied by an        // alphabet then replace it with alphabet        if (s[i].charCodeAt(0) < 97)            s = s.substring(0,i)+ c[nu_c++]+s.substring(i+1);         // Else replace it with a number        else        s = s.substring(0,i)+ c[al_c++]+s.substring(i+1);    }     // Return the sorted string    return s;} // Driver codevar s = "d4c3b2a1";document.write( sort(s)); // This code is contributed by rutvik_56.</script>
a1b2c3d4
 
Time complexity: O(N * log(N)) where N is the length of the string. 
princiraj1992
ankthon
HarshitGargjpr
sanjeev2552
rutvik_56
frequency-counting
Sorting
Strings
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexities of all Sorting Algorithms
Merge two sorted arrays
Count Inversions in an array | Set 1 (Using Merge Sort)
Sort an array of 0s, 1s and 2s | Dutch National Flag problem
Radix Sort
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack