Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 1da5b39

Browse filesBrowse files
authored
Sort a stack using recursion
1 parent 229f8d6 commit 1da5b39
Copy full SHA for 1da5b39

File tree

Expand file treeCollapse file tree

1 file changed

+101
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+101
-0
lines changed
Open diff view settings
Collapse file

‎Sorting a Stack using Recursion‎

Copy file name to clipboard
+101Lines changed: 101 additions & 0 deletions
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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.