Bubble Sort in Python3

0
def bubble_sort(list):
for i in range(len(list)):
    for j in range(len(list)-1):
        if list[j] > list[j+1]:
                list[j], list[j+1] = list[j+1], list[j]
        else:
            continue

I just did this bubble sort, but I ended up realizing that it does some unnecessary interactions because of the greater (i), I would like to know how to stop all interactions when the list is sorted / know when the list is going to be sorted

    
asked by anonymous 04.07.2018 / 14:55

1 answer

3

How about using a flag control to determine if the list has been sorted completely:

def bubble_sort( lst ):
    ok = False
    while not ok:
        ok = True
        for i in range(len(lst)-1):
            if lst[i] > lst[i + 1]:
                lst[i], lst[i + 1] = lst[i + 1], lst[i]
                ok = False
    return lst

print(bubble_sort([7,6,5,4,9,1,6,2,4,9,0,3]))

Output:

[0, 1, 2, 3, 4, 4, 5, 6, 6, 7, 9, 9]

In% with%, all this is already done and in the practical world, there is no need for such an implementation.

All this paraphernalia can be replaced simply by:

lst = [7,6,5,4,9,1,6,2,4,9,0,3]
print(sorted(lst))

Output:

[0, 1, 2, 3, 4, 4, 5, 6, 6, 7, 9, 9]
    
04.07.2018 / 19:31