Mar-24-2024, 07:57 AM
I think what you want to do is a bubble sort. Or maybe you want to know how sorted() works?
Your code doesn't work and seems complicated.
This implementation of the bubble sort may help you visualise the way bubble sort works.
Your code doesn't work and seems complicated.
This implementation of the bubble sort may help you visualise the way bubble sort works.
from random import randint frogs = [randint(0, 20) for i in range(10)] #repeating loop len(frogs)(number of elements) number of times moves = 0 for j in range(len(frogs)): #initially swapped is false swapped = False i = 0 while i<len(frogs)-1: #comparing the adjacent elements if frogs[i]>frogs[i+1]: #swapping frogs[i],frogs[i+1] = frogs[i+1],frogs[i] #Changing the value of swapped swapped = True moves +=1 i = i+1 print (f'frogs = {frogs}, i = {i}, moves = {moves}') #if swapped is false then the list is sorted #we can stop the loop if swapped == False: break