Skip to content

Instantly share code, notes, and snippets.

@seemaullal
Last active January 2, 2018 21:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seemaullal/be776dd3de4a03593ea0 to your computer and use it in GitHub Desktop.
Save seemaullal/be776dd3de4a03593ea0 to your computer and use it in GitHub Desktop.
Sorting a Stack Without Additional Data Structures

Before you started coding, you should have tried to think about this problem visually. It would probably help to actually make a stack and then an empty helper stack and think about how you can move elements around until one of the stacks contains all the elements in sorted order.

Here is an explanation of how the solution works– this is just an explanation of the algorithm and contains no code (at one point the video says that 8 is smaller than 2 instead of 8 is bigger than 2 but the solution is still correct):


(click on the image to be taken to the video)

The general idea is that you always pop the top element of the stack which you are sorting. You want to add this to the helper stack but first need to make sure that doing so won't make the helper stack unsorted.

When all elements from the original stack are in the helper stack (i.e. the original stack is empty), you need to assign the original stack to the sorted helper stack. Doing this can be a little confusing but remember that the Stack data structure only has knowledge of its top element. Each element then has a link/pointer to the element below it.So all we have ot do is assign the top of the original stack to the top of the sorted helper stack and we will be finished.

Here is one Javascript solution to this problem:

Stack.prototype.sort = function() {
    var helperStack = new Stack();
    while (!this.isEmpty()) {
        var curr = this.pop();
        while (!helperStack.isEmpty() && helperStack.peek() > curr) {
            this.push(helperStack.pop());
        }
        helperStack.push(curr);
    }
    this.top = helperStack.top;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment