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 going through the array once, ie you are just looping out of the Bubblesort loop.
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]
It's pretty much the same as yours:
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 ordered. So the need for the outermost loop and the not_sorted
variable.
This link here has the algorithm explained step-by-step in a very nice way.
link