Given a string of characters. The task is to write a program to print the characters of this string in sorted order using stack.
Input: str = "geeksforgeeks" Output: eeeefggkkorss Input: str = "hello395world216" Output: 123569dehllloorw
- Initialize two stacks, one stack and other tempstack.
- Insert the first character of the string in the stack.
- Iterate for all the characters in the string
- if the ith character is greater than or equal to the top element of the stack, then push the element.
- 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:
An efficient approach using hashing has been implemented in this post
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Sort string of characters
- Sort a string according to the frequency of characters
- Sort groups of numbers and characters separately in a String
- Sort a stack using a temporary stack
- Stack | Set 3 (Reverse a string using stack)
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- Sort a stack using recursion
- Sort the given stack elements based on their modulo with K
- Minimal moves to form a string by adding characters or appending string itself
- Sum of the alphabetical values of the characters of a string
- Check if the characters of a given string are in alphabetical order
- Average of ASCII values of characters of a given string
- How to remove all non-alphanumeric characters from a string in Java
- Find the character made by adding all the characters of the given string
- Program to find the XOR of ASCII values of characters in a string
- Reduce the string by removing K consecutive identical characters
- Count characters in a string whose ASCII values are prime
- Count pairs of characters in a string whose ASCII value difference is K
- Sort the given string using character search
- Comparison among Bubble Sort, Selection Sort and Insertion Sort
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.