Bubble Sort in Python3

Asked

Viewed 294 times

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 made this Bubble Sort, but I just realized that it makes some unnecessary interactions because of the is greater(i), I wonder how to stop all interactions when the list is sorted / know when the list will be sorted

  • The range should go from 0 to 0 i - 1. Then you’d have a good optimization. And the else is really unnecessary =)

  • I think this answer is worth reading: https://answall.com/a/311812/64969

  • I tested in 2 lists but only worked in one, in the other still lacked a value in the middle to be ordered

1 answer

3


How about using a flag to determine whether the list has been ordered in full:

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]))

Exit:

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

In Python, all this is already ready and in the practical world, there is no need for such 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))

Exit:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.