How to sort integers in a stack in ascending order

Hi, i am pretty much new in C++ programming and i have to do stack exercises. Can someone write a simple code of sorting the elements in ascending order in a stack. Thank you.
Hi, you are pretty much new in C++ programming and you have to do stack exercises.
you write a simple code of sorting the elements in ascending order in a stack.
Thank I.
Don't be too offended. the only way to learn this kind of stuff is to do it, struggle through it.

However, I wouldn't say sorting a stack is exactly a neophyte exercise. Remember the things you can do with a stack: push an element, pop an element, and look at the top element.

In order to sort it, you will need one other stack and a single temp variable. You might also want to keep track of how many items there are to be sorted (hint).

There are a number of ways to do it, but I suggest something along the lines of a selection/insertion sort. Find the smallest element and put it in its place. Repeat until there are no more elements to sort. (Hint.)

Good luck.
Here are the steps:

- You have to use two stacks. One is full of given elements. Other is empty.
- Pop the first element and store it in an array.
- Pop out remaining elements and compare it with the element stored in array. If you find bigger element, store it in the empty stack. But if it is smaller, replace the array element with the smaller one, and push the array element in the other stack. Repeat this for all elements in the stack.
- Once the stack is empty, repeat this process for the other stack, until it is empty.
- Keep on going until you get both stacks empty.
- Resulting array is the sorted list in ascending order.

Hope this helps.
You've introduced an array.
You've introduced an array.


You are right. Using a third stack in place of array should do it. Since stack is a LIFO structure, you might need to adjust based on the required ordering.
You don't need more than one additional stack.
Topic archived. No new replies allowed.