Search code examples
javaalgorithmsortingstackin-place

Algorithm to sort stack in place


Which sorting algorithms would be good to sort a Stack for space efficiency? I need to sort a stack 'in place.' Also my understanding of 'in place' algorithms was that they don't use any additional data structures - is this correct?

I know this is similar to this question but I'm wondering if it would be different for stacks? I know stacks can just be a type of linkedlist, but does the fact that you can only access the top change how you would do it?


Solution

  • You will have to omit the "in-place" qualifier if your intent is to sort the stack using only stack operations (you will have to have another stack). An in-place algorithm is an algorithm which transforms its input using no other data structures. However, a small amount of extra storage space is allowed for intermediary/temporary variables.

    If you omit the "in-place" qualifier you can find your answer here: How to sort a stack using only stack operations? (sorts a stack using an additional helper stack)

    If you retain the qualifier then sorting the stack is only possible on the implementation level, and not by using stack operations.