namespace chapter_4
{
class Challenge5_1
{
static Stack<int> sortStack(Stack<int> stack, int size)
{
//1. Use a second tempStack.
//2. Pop value from mainStack.
//3. If the value is greater or equal to the top of tempStack, then push the value in tempStack
//else pop all values from tempStack and push them in mainStack and in the end push value in tempStack and repeat from step 2.
//till mainStack is not empty.
//4. When mainStack will be empty, tempStack will have sorted values in descending order.
//5. Now transfer values from tempStack to mainStack to make values sorted in ascending order.
Stack<int> tempStack = new Stack<int>();
while (stack.Count != 0)
{
int value = stack.Pop();
if ((tempStack.Count > 0) && (value >= tempStack.Peek()))
{
tempStack.Push(value);
}
else
{
while (tempStack.Count != 0)
{
stack.Push(tempStack.Pop());
}
tempStack.Push(value);
}
}
//Transfer from tempStack => stack
while (tempStack.Count != 0)
{
stack.Push(tempStack.Pop());
}
return stack;
}
static void ShowStack(Stack<int> stack)
{
while (stack.Count != 0)
{
Console.Write("\t" + stack.Pop());
}
}
static void Main(string[] args)
{
Stack<int> stack = new Stack<int>();
stack.Push(2);
stack.Push(97);
stack.Push(4);
stack.Push(42);
stack.Push(12);
stack.Push(60);
stack.Push(23);
ShowStack(sortStack(stack, 7));
}
}
}