Bubble Sort on Python3
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 ended up realizing that it makes some unnecessary interactions on account of for greater (I), I would like to know how to stop all interactions when the list is sorted / know when the list will be sorted
0
Author: Angelo Gonçalves Salles, 2018-07-04
1 answers
How about using a control flag 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 Python
, all this is already ready, 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]
3
Author: Lacobus, 2018-07-04 17:38:27