> For the complete documentation index, see [llms.txt](https://aaronice.gitbook.io/lintcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://aaronice.gitbook.io/lintcode/data_structure/stack_sorting.md).

# Stack Sorting

## Question

Sort a stack in ascending order (with biggest terms on top).

You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure (e.g. array).

**Example**

Given stack =

```
| |
|3|
|1|
|2|
|4|
-
```

return:

```
| |
|4|
|3|
|2|
|1|
-
```

The data will be serialized to \[4,2,1,3]. The last element is the element on the top of the stack.

**Challenge**

`O(n^2)` time is acceptable.

## Analysis

根据题目提示，可以设想利用另一个stack作为临时储存空间，设定的规则是： 1. 从origin stack中不断pop() element 2. 对于helper stack，如果helper stack peek() < element，则将helper stack中的元素全部转移到origin stack 3. 再将element push()到helper stack中 4. 不断重复上述步骤，直到origin stack isEmpty 5. 最后，所有的元素已经按照descending order排序好（smallest on top），只需将其转移到origin stack，则origin stack即为所需排序

时间复杂度为O(n^2)，空间复杂度为O(n)

## Solution

```java
public class Solution {
    /**
     * @param stack an integer stack
     * @return void
     */
    public void stackSorting(Stack<Integer> stack) {
        Stack<Integer> helpStack = new Stack<Integer>();
        while (!stack.isEmpty()) {
            int element = stack.pop();
            while (!helpStack.isEmpty() && helpStack.peek() < element) {
                stack.push(helpStack.pop());
            }
            helpStack.push(element);
        }
        while (!helpStack.isEmpty()) {
            stack.push(helpStack.pop());
        }
    }
}
```

## Reference

* [IBM interview question : how to sort a stack?](http://stackoverflow.com/questions/4826311/ibm-interview-question-how-to-sort-a-stack)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://aaronice.gitbook.io/lintcode/data_structure/stack_sorting.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
