Skip to content

Commit

Permalink
Merge pull request narayancseian#56 from Kishun21/main
Browse files Browse the repository at this point in the history
Create Recursive solution to sort a stack.py
  • Loading branch information
narayancseian authored Oct 6, 2022
2 parents 82ef7b0 + b090e68 commit 0d52b6a
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Stack/Recursive solution to sort a stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from collections import deque


# Insert the given key into the sorted stack while maintaining its sorted order.
# This is similar to the recursive insertion sort routine
def sortedInsert(stack, key):

# base case: if the stack is empty or
# the key is greater than all elements in the stack
if not stack or key > stack[-1]:
stack.append(key)
return

''' We reach here when the key is smaller than the top element '''

# remove the top element
top = stack.pop()

# recur for the remaining elements in the stack
sortedInsert(stack, key)

# insert the popped element back into the stack
stack.append(top)


# Recursive method to sort a stack
def sortStack(stack):

# base case: stack is empty
if not stack:
return

# remove the top element
top = stack.pop()

# recur for the remaining elements in the stack
sortStack(stack)

# insert the popped element back into the sorted stack
sortedInsert(stack, top)


if __name__ == '__main__':

A = [5, -2, 9, -7, 3]

stack = deque(A)

print('Stack before sorting:', list(stack))
sortStack(stack)
print('Stack after sorting:', list(stack))

0 comments on commit 0d52b6a

Please sign in to comment.