CBSE Class 12 Computer Science Question 15 of 26

Data Structures in Python — Question 16

Back to all questions
16
Question

Question 16

Write a Python program to sort a Stack in ascending order without using an additional Stack.

Solution
def pushSorted(s, num):
	if len(s) == 0 or num > s[-1]:
		s.append(num)
		return
	else:
		t = s.pop()
		pushSorted(s, num)
		s.append(t)

def doSort(s):
	if len(s) != 0:
		t = s.pop()
		doSort(s)
		pushSorted(s, t)

s = []
s.append(12)
s.append(5)
s.append(-3)
s.append(4)
s.append(10)

print("Stack before sorting: ")
print(s)

doSort(s)

print("\nStack after sorting: ")
print(s)
Output
Stack before sorting: 
[12, 5, -3, 4, 10]

Stack after sorting:
[-3, 4, 5, 10, 12]
Answer

def
pushSorted
(
s
,
num
):
if
len
(
s
)
==
0
or
num
>
s
[
-
1
]:
s
.
append
(
num
)
return
else
:
t
=
s
.
pop
()
pushSorted
(
s
,
num
)
s
.
append
(
t
)
def
doSort
(
s
):
if
len
(
s
)
!=
0
:
t
=
s
.
pop
()
doSort
(
s
)
pushSorted
(
s
,
t
)
s
=
[]
s
.
append
(
12
)
s
.
append
(
5
)
s
.
append
(
-
3
)
s
.
append
(
4
)
s
.
append
(
10
)
print
(
"Stack before sorting: "
)
print
(
s
)
doSort
(
s
)
print
(
"
\n
Stack after sorting: "
)
print
(
s
)
Output
Stack before sorting:
[12, 5, -3, 4, 10]

Stack after sorting:
[-3, 4, 5, 10, 12]