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.
- 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:
C++
#include <bits/stdc++.h>
using namespace std;
void printSorted(string s, int l)
{
stack< char > Stack;
stack< char > tempstack;
Stack.push(s[0]);
for ( int i = 1; i < l; i++)
{
int a = s[i];
int b = Stack.top();
if ((a - b) >= 1 or (a == b))
Stack.push(s[i]);
else if ((b - a) >= 1)
{
while ((b - a) >= 1)
{
tempstack.push(Stack.top());
Stack.pop();
if (Stack.size() > 0)
b = Stack.top();
else
break ;
}
Stack.push(s[i]);
while (tempstack.size() > 0)
{
Stack.push(tempstack.top());
tempstack.pop();
}
}
}
string answer;
while (Stack.size() > 0)
{
answer = Stack.top() + answer;
Stack.pop();
}
cout << answer << endl;
}
int main()
{
string s = "geeksforgeeks" ;
int l = s.length();
printSorted(s, l);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
public static void printSorted(String s, int l)
{
Stack<Character> stack = new Stack<Character>();
Stack<Character> tempstack = new Stack<Character>();
stack.push(s.charAt( 0 ));
for ( int i = 1 ; i < l; i++)
{
int a = s.charAt(i);
int b = ( int )(( char )stack.peek());
if ((a - b) >= 1 || (a == b))
{
stack.push(s.charAt(i));
}
else if ((b - a) >= 1 )
{
while ((b - a) >= 1 )
{
tempstack.push(stack.peek());
stack.pop();
if (stack.size() > 0 )
{
b = ( int )(( char )stack.peek());
}
else
{
break ;
}
}
stack.push(s.charAt(i));
while (tempstack.size() > 0 )
{
stack.push(tempstack.peek());
tempstack.pop();
}
}
}
String answer = "" ;
while (stack.size() > 0 )
{
answer = stack.peek()+answer;
stack.pop();
}
System.out.println(answer);
}
public static void main(String []args)
{
String s = "geeksforgeeks" ;
int l = s.length();
printSorted(s, l);
}
}
|
Python3
def printSorted(s, l):
stack = []
tempstack = []
stack.append(s[ 0 ])
for i in range ( 1 , l):
a = ord (s[i])
b = ord (stack[ - 1 ])
if ((a - b)> = 1 or (a = = b)):
stack.append(s[i])
elif ((b - a)> = 1 ):
while ((b - a)> = 1 ):
tempstack.append(stack.pop())
if ( len (stack)> 0 ):
b = ord (stack[ - 1 ])
else :
break
stack.append(s[i])
while ( len (tempstack)> 0 ):
stack.append(tempstack.pop())
print (''.join(stack))
s = "geeksforgeeks"
l = len (s)
printSorted(s, l)
|
C#
using System;
using System.Collections;
class GFG {
static void printSorted( string s, int l)
{
Stack stack = new Stack();
Stack tempstack = new Stack();
stack.Push(s[0]);
for ( int i = 1; i < l; i++)
{
int a = s[i];
int b = ( int )(( char )stack.Peek());
if ((a - b) >= 1 || (a == b))
stack.Push(s[i]);
else if ((b - a) >= 1)
{
while ((b - a) >= 1)
{
tempstack.Push(stack.Peek());
stack.Pop();
if (stack.Count > 0)
b = ( int )(( char )stack.Peek());
else
break ;
}
stack.Push(s[i]);
while (tempstack.Count > 0)
{
stack.Push(tempstack.Peek());
tempstack.Pop();
}
}
}
string answer = "" ;
while (stack.Count > 0)
{
answer = stack.Peek() + answer;
stack.Pop();
}
Console.WriteLine(answer);
}
static void Main() {
string s = "geeksforgeeks" ;
int l = s.Length;
printSorted(s, l);
}
}
|
Javascript
<script>
function printSorted(s, l)
{
var Stack = [];
var tempstack = [];
Stack.push(s[0].charCodeAt(0));
for ( var i = 1; i < l; i++)
{
var a = s[i].charCodeAt(0);
var b = Stack[Stack.length-1];
if ((a - b) >= 1 || (a == b))
Stack.push(s[i].charCodeAt(0));
else if ((b - a) >= 1)
{
while ((b - a) >= 1)
{
tempstack.push(Stack[Stack.length-1]);
Stack.pop();
if (Stack.length > 0)
b = Stack[Stack.length-1];
else
break ;
}
Stack.push(s[i].charCodeAt(0));
while (tempstack.length > 0)
{
Stack.push(tempstack[tempstack.length-1]);
tempstack.pop();
}
}
}
var answer = "" ;
while (Stack.length > 0)
{
answer = String.fromCharCode(Stack[Stack.length-1]) + answer;
Stack.pop();
}
document.write( answer)
}
var s = "geeksforgeeks" ;
var l = s.length;
printSorted(s, l);
</script>
|
Complexity Analysis:
- Time Complexity: O(n2)
- Auxiliary Space: O(n)
An efficient approach using hashing has been implemented in this post
Last Updated :
26 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...