Apparently you want to implement Bubblesort.
A possible implementation of Bubblesort:
def bubblesort(list):
not_sorted = True
while not_sorted:
not_sorted = False
for i in range(0, len(list)-1):
if list[i] > list[i+1]:
not_sorted = True
list[i], list[i+1] = list[i+1], list[i]
return list
print(bubblesort([1, 3, 2, 10, 2, 4]))
The problem with your algorithm is that you are only passing the array once, meaning you are only iterating the loop from outside of Bubblesort.
Notice that part of my code:
for i in range(0, len(list)-1):
if list[i] > list[i+1]:
not_sorted = True
list[i], list[i+1] = list[i+1], list[i]
is pretty much the same as your:
while x < (len(L) -1):
if L[x] > L[x+1]:
L[x],L[x+1] = L[x+1],L[x]
The difference is that you have to do this part while the array is not sorted. Hence the need for more out loop and variable not_sorted
.
This link here has the algorithm explained step-by-step in a very nice way.
http://www.cs.armstrong.edu/liang/animation/web/BubbleSort.html
I tried it based on yours but it didn’t work -> https://pastebin.com/Ku2TpTMg
– Ed S
You forgot to increment the
x
. Putsx = x+1
after the lineL[x],L[x+1] = L[x+1],L[x]
, and outside the scope ofif
.– Max Fratane
grateful! I’m trying to learn!
– Ed S
does not yet work -> https://pastebin.com/1BgUF7Fe
– Ed S
for me now the algorithms are the same!
– Ed S