优点:算法简单直接
缺点:算法复杂度为O(n^2^)
代码实现
def bubble_sort(lst):
for i in range(len(lst)-1,0,-1):
for j in range(i):
if lst[j] > lst[j+1]:
tmp = lst[j]
lst[j] = lst[j+1]
lst[j+1] = tmp
return lst
5行代码实现
It is often useful to swap the values of two variables. With conventional assignments, you have to use a temporary variable. This solution is cumbersome; tuple assignment is more elegant:
def bubble_sort(lst):
for i in range(len(lst)-1,0,-1):
for j in range(i):
if lst[j] > lst[j+1]:
lst[j],lst[j+1] = lst[j+1],lst[j] # use tuple assignment
return lst