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.)
- 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.
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.