Bubble sort, also known as sinking sort, is a sorting algorithm that repeatedly steps through a list, compares adjacent pairs and swaps them if they are not in the right order. The pass through the list is repeated, until the sorting is complete. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list.
This is my
def BubbleSort(l): 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] return l
print(BubbleSort([1,5,-5,0,10,100])) [-5, 0, 1, 5, 10, 100]
With some detailed advice, here is a second solution, limited to using one list comprehension:
def BubbleSort(l): [l.append(l.pop(0) if i == len(l) - 1 or l < l else l.pop(1)) for j in range(0, len(l)) for i in range(0, len(l))]
which somewhat outputs the same:
l = [1,5,-5,0,10,100] BubbleSort(l) print(l) [-5, 0, 1, 5, 10, 100]
Would you be so kind and review it? I'd also like to know about time/space complexities, if you possibly had time.