Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created October 7, 2019 18:03
Show Gist options
  • Save dgodfrey206/12316759034ec770e461a7ee2f595140 to your computer and use it in GitHub Desktop.
Save dgodfrey206/12316759034ec770e461a7ee2f595140 to your computer and use it in GitHub Desktop.
Sort a stack using recursion
#include <iostream>
#include <string>
#include <vector>
#include<bits/stdc++.h>
using namespace std;
void insertSorted(stack<int>& s, int e) {
stack<int> temp;
while (true) {
if (s.empty() || e >= s.top()) {
s.push(e);
while (!temp.empty()) {
s.push(temp.top());
temp.pop();
}
return;
}
temp.push(s.top());
s.pop();
}
}
void sortStack(stack<int>& s) {
if (s.empty()) return;
int t = s.top(); s.pop();
sortStack(s);
insertSorted(s, t);
}
int main()
{
stack<int>s;
s.push(5);s.push(4);s.push(2);s.push(-4);s.push(54);s.push(0);
sortStack(s);
while(!s.empty()){
cout<<s.top()<<" ";
s.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment