Skip to content

Instantly share code, notes, and snippets.

@lawliet89
Created January 27, 2014 21:52
Show Gist options
  • Save lawliet89/8658109 to your computer and use it in GitHub Desktop.
Save lawliet89/8658109 to your computer and use it in GitHub Desktop.
Sort numbers using only two stacks
#include <stack>
#include <iostream>
#include <vector> // for lazy man initialisation
using namespace std;
/*
Using two stacks ONLY, sort a stack with biggest item on top
*/
template <typename T> stack<T> stackSort(stack<T> items);
int main() {
// Lazy to push manually to stack.
vector<int> input = {5,10,15,20,25,50,40,30,20,10,9524,878,17,1,99,
18785,3649,164,94, 123,432,654,3123,654,2123,543,131,653,123,533,
1141,532,213,2241,824,1124,42,134,411, 0,
491,341,1234,527,388,245,1992,654,243,987, -9,-66,54,98,-999};
stack<int> inputStack;
for (int number : input) {
inputStack.push(number);
}
stack<int> sorted = stackSort(inputStack);
while(!sorted.empty()) {
cout << sorted.top() << " ";
sorted.pop();
}
cout << endl;
}
template <typename T> stack<T> stackSort(stack<T> items) {
stack<T> sorted;
while (!items.empty()) {
T item = items.top();
items.pop();
int counter = 0;
while (!sorted.empty() && sorted.top() < item) {
items.push(sorted.top());
sorted.pop();
++counter;
}
sorted.push(item);
for (int i = 0; i < counter; ++i) {
sorted.push(items.top());
items.pop();
}
}
return sorted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment