3.6 Write a program to sort a stack in ascending order (with biggest items on top). You may use additional stacks to hold items, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations:push, pop, peek and isEmpty.
Approach 1: use another stack - O(n^2)
stack<int> sort(stack<int> &s) {
stack<int> r;
while (!s.empty()) {
int x = s.top();
s.pop();
while (!r.empty() && r.top() > x) {
s.push(r.top());
r.pop();
}
r.push(x);
}
return r;
}
Approach 2: Recursive - O(n^2)
void insert(stack<int> &s, int x) {
if (s.empty()) {
s.push(x);
} else if (s.top() < x) {
s.push(x);
} else {
int y = s.top();
s.pop();
insert(s, x);
s.push(y);
}
}
void sort(stack<int> &s) {
if (!s.empty()) {
int x = s.top();
s.pop();
sort(s);
insert(s, x);
}
}