Sort string of characters using Stack

Given a string of characters. The task is to write a program to print the characters of this string in sorted order using stack.

Examples:

Input: str = "geeksforgeeks" 
Output: eeeefggkkorss

Input: str = "hello395world216"
Output: 123569dehllloorw

Approach:



  • Initialize two stacks, one stack and other tempstack.
  • Insert the first character of the string in the stack.
    1. Iterate for all the characters in the string
    2. if the ith character is greater than or equal to the top element of the stack, then push the element.
    3. if the ith character is not greater, then push all the elements of the stack into tempstack, and then push the character into the stack. After this, push all the greater elements of tempstack to stack.

Print the all elements of the stack in reverse order when the iteration is completed.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to sort 
# string of characters using stack 
  
  
# function to print the characters 
# in sorted order 
def printSorted(s, l): 
      
    # primary stack
    stack =[] 
      
    # secondary stack
    tempstack =[] 
      
    # append first character  
    stack.append(s[0])
      
    # iterate for all character in string 
    for i in range(1, l):
          
        # i-th character ASCII 
        a = ord(s[i])
          
        # stack's top element ASCII 
        b = ord(stack[-1]) 
          
        # if greater or equal to top element 
        # then push to stack 
        if((a-b)>= 1 or (a == b)):
            stack.append(s[i]) 
              
        # if smaller, then push all element 
        # to the temporary stack 
        elif((b-a)>= 1):
              
            # push all greater elements 
            while((b-a)>= 1):
                  
                # push operation 
                tempstack.append(stack.pop())
                  
                # push till the stack is not-empty 
                if(len(stack)>0):
                    b = ord(stack[-1])
                else:
                    break
                      
            # push the i-th character 
            stack.append(s[i])
              
            # push the tempstack back to stack 
            while(len(tempstack)>0):
                stack.append(tempstack.pop()) 
                  
    # print the stack in reverse order 
    print(''.join(stack)) 
  
  
# Driver Code
s = "geeksforgeeks" 
l = len(s)
printSorted(s, l)

chevron_right


Output:

eeeefggkkorss

An efficient approach using hashing has been implemented in this post



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.