Practice Problem
- Stack
- Recursion
Pop one element recursively, sort the rest, then insert the popped element in sorted position.
O(n^2)
O(n)
import java.util.*;
class Solution {
public void sortStack(Stack<Integer> stack) {
if (stack.isEmpty()) return;
int top = stack.pop();
sortStack(stack);
insertSorted(stack, top);
}
private void insertSorted(Stack<Integer> stack, int val) {
if (stack.isEmpty() || stack.peek() <= val) {
stack.push(val);
return;
}
int top = stack.pop();
insertSorted(stack, val);
stack.push(top);
}
}