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