How to sort using STACK in C++?

Anyone can help me with this algorithm?

1 set up stack in and print it
2 while stack in is not empty repeat
2.1 max = in.pop
2.2 while there are still element in stack in repeat
2.2.1 value = in.pop
2.2.2 if value > max
2.2.2.1 temp.push(max)
2.2.2.2 max = value
2.2.3 else
2.2.3.1 temp.push(value)
2.3 in = temp
2.4 out.push(max)
2.5 temp.clear
3 print sorted stack
You seem to have the algorithm. All you need to do is code it.
I am not well in C++......I already try to code it but it still not working...someone can help me?
Below is my code...

#include <iostream>
#include <stack>
using namespace std;

int main ()
{
stack <int> in,out,temp;

int num[] = {50,10,60,40,80,20,70};

cout<<"Unsorted numbers in stack in :"<<endl;

for (int i=0; i<7; i++)
{
in.push(num[i]);
cout<<in.top()<<endl; //print stack in
}

cout << endl;

while (!in.empty())
{
int max=in.top();

while (!in.empty())
{
in.pop();
int value=in.top();

if (value > max)
{
temp.push(max);
max=value;
}
else
{
temp.push(value);
}
}
in = temp;
out.push(max);
// temp->clear();
}

cout<<"Sorted numbers in stack out :";

for (int i=0; i<7; i++)
{
cout<<out.top()<<endl; //print stack in
out.pop();
}

return 0;
}
Please use the code format tags to format your code, it's impossible to read it without formatting.

The big mistake is when in the outer while loop where you set max, you don't pop the stack.

You do see temp stack needs to be cleared, but it's a bit tricky to do so. A principle that's introduced in C++ is to declare variables where used. Now, you've declared temp at the top of the program, but it isn't used there, it's used in the outer loop, so move the declaration there. When the outer loop ends, it cleans up temp and so does the clear for you.

I hope that helps. That was an excellent initial attempt.
Topic archived. No new replies allowed.