Files
2024-08-31 12:07:21 +03:00

94 lines
3.0 KiB
Python

#Assignment 2 - sort: bubble and strand
#https://github.com/cs-ubbcluj-ro/FP/blob/main/src/assignments/A2.md
import random
def GUI():
current_list=[]
while True:
print("1 - Generate a List")
print("2 - Show Current List")
print("3 - Bubble Sort")
print("4 - Strand Sort")
print("0 - Exit")
value = int(input())
match value:
case 1:
n=int(input("Select lenght of the list: "))
current_list = generate_list(n)
print("Generated list: {}\n".format(current_list))
case 2:
show_list(current_list)
case 3:
steps=int(input("Please select the number of steps: "))
current_list=bubble_sort(current_list,steps)
case 4:
steps=int(input("Please select the number of steps: "))
current_list=strand_sort(current_list,steps)
case 0:
exit()
case _:
print("Invalid command")
def bubble_sort(l,step):
print("Starting list: {}".format(l))
current_step=0
for i in range(len(l)-1):
for j in range(len(l)-1-i):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
current_step+=1
if current_step % step == 0:
print("List after {} steps: {}".format(current_step,l))
print("Sorted list: {}\n".format(l))
return l
def strand_sort(l,step):
print("Starting list: {}\n".format(l))
current_step=0
aux_list=[]
final_list=[]
while l:
aux_list=[]
aux_list.append(l.pop(0))
current_step+=1
strand_sort_message(current_step,l,aux_list,final_list,step)
for i in l.copy():
if aux_list[-1] <= i:
aux_list.append(l.pop(l.index(i)))
current_step+=1
strand_sort_message(current_step,l,aux_list,final_list,step)
if final_list:
i=0
while aux_list:
if aux_list[-1]>final_list[i]:
i+=1
else:
final_list.insert(i,aux_list[-1])
aux_list.pop()
current_step+=1
strand_sort_message(current_step,l,aux_list,final_list,step)
i=0
else:
final_list=aux_list.copy()
aux_list.clear()
current_step+=1
strand_sort_message(current_step,l,aux_list,final_list,step)
print("Sorted list: {}\n".format(final_list))
return final_list
def strand_sort_message(current_step,l,aux_list,final_list,step):
if current_step%step==0:
print("Lists after {} steps:".format(current_step))
print("Starting list: {}".format(l))
print("Working list: {}".format(aux_list))
print("Final list: {}\n".format(final_list))
def generate_list(n):
return [random.randint(0,100) for _ in range(n)]
def show_list(l):
print("Current list: {}\n".format(l))
if __name__=="__main__":
GUI()