# Stack Sort

• 02-11-2002
fluf
Stack Sort
Does anyone know how to sort a stack in alphabetical order using only stack operations(push(),pop(), etc)? Here is the code so far. Any ideas? Please email me at jtchamit@coe.neu.edu.

#include <iostream>
#include <string>
#include <stack>

using namespace std;

int main()

{

stack <string> initial;

stack <string> smallest;

string name;
string comp1;
string comp2;

int count=0,
y=0;

int smallcount=0;

cerr << "Enter name\n";
cerr << "Enter -1 to quit: ";
cin >> name;

while(name != "-1")

{

initial.push(name);

count++;

cerr << "Enter name\n";
cerr << "Enter -1 to quit: ";
cin >> name;

}

/* initial sort */

for (y=1 ; y <= count-1 ; y++)

{

comp1=initial.top();
initial.pop();

comp2=initial.top();
initial.pop();

cout<<"comp1: "<<comp1<<endl;
cout<<"comp2: "<<comp2<<endl;

if(comp1 < comp2)

{

smallest.push(comp1);
smallcount++; initial.push(comp2);

}

if(comp1 > comp2)

{

smallest.push(comp2);
smallcount++;
initial.push(comp1);

}

}

cout<<"\nsmallest values: "<<smallcount<<endl;

while(!smallest.empty())

{

comp1=smallest.top();
smallest.pop();
cout<<comp1<<" ";

}

cout<<"\nlargest value: \n";

while(!initial.empty())

{

comp1=initial.top();
initial.pop();
cout<<comp1<<" ";

}

cout<<endl;

return 0;

}
• 02-11-2002
sean
I've never done it before, but i would suggest just simply sorting them with an alphabetizing function, and then have a functin that pushes them on the stack. A general rule with functions - Do one thing, Do it well (An inside joke for DavidP - Do it, Do it right, Do it right now). Try breaking your code up into smaller pieces, with one job for each function/framework.
• 02-11-2002
GeekSeb
As Far As i Know, Stacks Arent Supposed to Be Sorted. But Anywho:

To Alphabetize, When adding the extra node to the stack, traverse your stack with two pointers, one to the element for checking and one to the previous element. When you find a spot for the new one to be inserted, then you do it. Then, no extra function is needed. Just Incorporate Into the Push() Function.
• 02-11-2002
samGwilliam
Surely sorting a stack defeats the object (the LIFO paradigm). Anyway, to do it you'll need two more stacks to hold out of order values while you sort. A bit like Towers of Hanoi.