代码
def BubbleSort(list):
len_l = len(list)
for i in range(len_l):
exchange = False#用于标记一次遍历是否交换
for j in range(len_l-1, i, -1):
if list[j] < list[j-1]:
list[j], list[j-1] = list[j-1], list[j]
exchange = True
if not exchange:#一次遍历无交换,说明有序
return list
print(BubbleSort([3,2,1,4]))
复杂度
- 时间复杂度:
- 最好,时间复杂度O(n)
- 最差,时间复杂度(n2)
- 平均,时间复杂度O(n2)
- 空间复杂度:O(1)