forked from narayancseian/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request narayancseian#56 from Kishun21/main
Create Recursive solution to sort a stack.py
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |