public static Stack<Integer> sort(Stack<Integer> stack) {
    if (stack == null || stack.isEmpty()) return stack;

    Stack<Integer> buffer = new Stack<Integer>();

    Integer tmp1 = null, tmp2 = null;

    while (!stack.isEmpty()) {
      tmp1 = stack.peek();
      while (!buffer.isEmpty() && buffer.peek() > tmp1) {
        stack.push(buffer.pop());
      }
      buffer.push(tmp1);
      while ((tmp2 = stack.pop()) != tmp1) {
        buffer.push(tmp2);
      }
    }

    return buffer;
  }