Sort a Stack using Recursion

In this problem, We have to write a code to sort a stack using recursion. We have to sort in a descending order (Top of the stack has the greatest element).

We don’t have to use any loop constructs ( for, while etc) or additional data structure.

For Example –

In this example, You can see after sorting the stack, the element which has greater value is at the top of the stack.

Sort a stack using recursion

This question is similar to reverse a stack using recursion. In this problem we don’t have to use extra stack to solve this problem. Before checking the solution, first try to solve this problem yourself.

At the end of this tutorial, I have also mentioned the video tutorial link.

Recursion vs Iteration

Programming Video Tutorials

Programming Questions on Stack

Sort a Stack using Recursion – Java Code

We know in a stack the element which we pushed at last is the first element to be popped out. It follows Last In First Out (LIFO) order.

To sort a stack, First we have to pop all the values of a stack recursively until the stack becomes empty. And then insert each values at correct position so that the stack will be sorted.

It means we have to use two recursive function to solve this problem.

The time complexity of this approach is O(n^2) and it’s space complexity is O(n).

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.