Created
October 7, 2019 18:03
-
-
Save dgodfrey206/12316759034ec770e461a7ee2f595140 to your computer and use it in GitHub Desktop.
Sort a stack using recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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