Sort a stack using recursion

Sort a stack using recursion

Solution:

Algorithm:

Sort (stack) Function

  • If stack is empty then
    • return ;
  • Set temp = stack.pop
  • Call Sort(stack)
  • Call function AddInSortedOrder(stack, temp)

AddInSortedOrder(stack, element) Function

  • If stack is empty or stack.top < element then,
    • stack.push (element)
    • return ;
  • Set temp = stack.pop
  • Call AddInSortedOrder(stack, element)
  • stack.push(temp)

Latest Source Code:
Github: StackSort.java


Output:

[18,3,1,40,7,10,-1]
[40,18,10,7,3,1,-1]
Author: Hrishikesh Mishra