[AlgoExpert] Sort Stack

Sort Stack

  • Time : O(n^2)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <vector>
using namespace std;

void balance(vector<int>& st, int v) {
if(st.empty() or st.back() <= v) {
st.push_back(v);
return;
}

int tp = st.back();
st.pop_back();
balance(st,v);
st.push_back(tp);
return;
}

vector<int> sortStack(vector<int> &st) {
if(st.empty()) return st;

int tp = st.back();
st.pop_back();
sortStack(st);

balance(st, tp);

return st;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/12/PS/AlgoExpert/sort-stack/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.