-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday20.py
More file actions
33 lines (24 loc) · 826 Bytes
/
day20.py
File metadata and controls
33 lines (24 loc) · 826 Bytes
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
def sort_stack(stack):
# Base case: If the stack is empty, return
if not stack:
return
# Remove the top element
top = stack.pop()
# Recursively sort the remaining stack
sort_stack(stack)
# Insert the top element back in sorted order
insert_the_ele(stack, top)
def insert_the_ele(stack, element):
# If the stack is empty or the element is greater than the top, push the element
if not stack or stack[-1] <= element:
stack.append(element)
return
# Remove the top element
top = stack.pop()
# Recursively call to find the right position for the element
insert_the_ele(stack, element)
# Push the removed element back
stack.append(top)
stack = [3, 1, 4, 2]
sort_stack(stack)
print(stack) # Output: [1, 2, 3, 4]