Skip to content

Commit 1da5b39

Browse files
authored
Sort a stack using recursion
1 parent 229f8d6 commit 1da5b39

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed

Sorting a Stack using Recursion

+101
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
def sortedInsert(s , element):
2+
3+
4+
5+
# Base case: Either stack is empty or newly inserted
6+
7+
# item is greater than top (more than all existing)
8+
9+
if len(s) == 0 or element > s[-1]:
10+
11+
s.append(element)
12+
13+
return
14+
15+
else:
16+
17+
18+
19+
# Remove the top item and recur
20+
21+
temp = s.pop()
22+
23+
sortedInsert(s, element)
24+
25+
26+
27+
# Put back the top item removed earlier
28+
29+
s.append(temp)
30+
31+
32+
# Method to sort stack
33+
34+
def sortStack(s):
35+
36+
37+
38+
# If stack is not empty
39+
40+
if len(s) != 0:
41+
42+
43+
44+
# Remove the top item
45+
46+
temp = s.pop()
47+
48+
49+
50+
# Sort remaining stack
51+
52+
sortStack(s)
53+
54+
55+
56+
# Push the top item back in sorted stack
57+
58+
sortedInsert(s , temp)
59+
60+
61+
# Printing contents of stack
62+
63+
def printStack(s):
64+
65+
for i in s[::-1]:
66+
67+
print(i , end=" ")
68+
69+
print()
70+
71+
72+
73+
if __name__=='__main__':
74+
75+
s = [ ]
76+
77+
s.append(30)
78+
79+
s.append(-5)
80+
81+
s.append(18)
82+
83+
s.append(14)
84+
85+
s.append(-3)
86+
87+
88+
89+
print("Stack elements before sorting: ")
90+
91+
printStack(s)
92+
93+
94+
95+
sortStack(s)
96+
97+
98+
99+
print("\nStack elements after sorting: ")
100+
101+
printStack(s)

0 commit comments

Comments
 (0)