Skip to content

Commit 12f8d7d

Browse files
authored
Create Stack Sorting
1 parent 03a4251 commit 12f8d7d

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

data_structures/stacks/Stack Sorting

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Stack:
2+
def __init__(self):
3+
self.items = []
4+
5+
def push(self, item):
6+
self.items.append(item)
7+
8+
def pop(self):
9+
if not self.is_empty():
10+
return self.items.pop()
11+
return None
12+
13+
def is_empty(self):
14+
return len(self.items) == 0
15+
16+
def peek(self):
17+
if not self.is_empty():
18+
return self.items[-1]
19+
return None
20+
21+
def size(self):
22+
return len(self.items)
23+
24+
def __str__(self):
25+
return str(self.items)
26+
27+
def sort_stack(original_stack):
28+
aux_stack = Stack()
29+
30+
while not original_stack.is_empty():
31+
# Pop the top element from the original stack
32+
temp = original_stack.pop()
33+
34+
# While the auxiliary stack is not empty and the top element
35+
# of the auxiliary stack is greater than temp
36+
while not aux_stack.is_empty() and aux_stack.peek() > temp:
37+
original_stack.push(aux_stack.pop())
38+
39+
# Push temp in the auxiliary stack
40+
aux_stack.push(temp)
41+
42+
# Transfer elements back to the original stack
43+
while not aux_stack.is_empty():
44+
original_stack.push(aux_stack.pop())
45+

0 commit comments

Comments
 (0)