Mar-24-2024, 06:14 PM
Following your private message:
I think perhaps you are concentrating on a list with only 4 elements, but that is not helpful.
You need to be able to sort any list.
Try this way to bubble sort:
I think perhaps you are concentrating on a list with only 4 elements, but that is not helpful.
You need to be able to sort any list.
Try this way to bubble sort:
from random import randint # Helper variables moves = 0 # set q = True or the while loop will not start q = True # make a random list # you can change the numbers here: randint(0, 20) and here: range(10) frogs = [randint(0, 20) for i in range(10)] print(f'Start situation frogs = {frogs}') # the while loop will keep going until there is nothing to swap around # then q = False and the while loop will stop # don't set: while True because True is always True, the while loop will not stop while q: q = False # Reset q for this pass # keep looping through the list until there is nothing left to swap for i in range(1, len(frogs)): if frogs[i - 1] > frogs[i]: # Swap the elements frogs[i - 1], frogs[i] = frogs[i], frogs[i - 1] q = True # Set q to True if a swap occurs moves +=1 print (f'frogs = {frogs}, i = {i}, moves = {moves}')