# Sort Stack ⇒ recursive good -

![](/files/UA12tLGkj5lhrxO0ox1i)

* n^2, n

```tsx
function sortStack(stack) {
  
  takeAllValues(stack);
  return stack;
}

function takeAllValues(stack, idx) {
  if (stack.length === 0) return stack;

  const top = stack.pop();
  takeAllValues(stack);

  sortInOrderAtEachStep(stack, top);
}

function sortInOrderAtEachStep(stack, valueToCompare) {
  if (stack.length === 0 || stack[stack.length - 1] <= valueToCompare) {
    stack.push(valueToCompare);
    return;
  }

  // take top
  const top = stack.pop();

  // sort element inside
  sortInOrderAtEachStep(stack, valueToCompare);

  // push top
  stack.push(top);
  
}

exports.sortStack = sortStack;
```


---

# Agent Instructions: 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:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/sort-stack-recursive-good.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
