冒泡法排序:
"""
冒泡法排序
"""
#一个数字列表,用于排序
l = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]
for i in range(len(l)): #从第1个数开始跟后面比较,
for j in range(i,len(l)):#用于比较的j,从i开始分别取值到最后一个。
if l[i] < l[j]: #如果当前值小于后面的值
l[i], l[j] = l[j], l[i] #当前值和和后的值做交换
print(f"{l}第{i+1}次") #查看每一次的结果
结果:
[50, 3, 38, 5, 44, 15, 36, 26, 27, 2, 46, 4, 19, 47, 48]第1次
[50, 48, 3, 5, 38, 15, 36, 26, 27, 2, 44, 4, 19, 46, 47]第2次
[50, 48, 47, 3, 5, 15, 36, 26, 27, 2, 38, 4, 19, 44, 46]第3次
[50, 48, 47, 46, 3, 5, 15, 26, 27, 2, 36, 4, 19, 38, 44]第4次
[50, 48, 47, 46, 44, 3, 5, 15, 26, 2, 27, 4, 19, 36, 38]第5次
[50, 48, 47, 46, 44, 38, 3, 5, 15, 2, 26, 4, 19, 27, 36]第6次
[50, 48, 47, 46, 44, 38, 36, 3, 5, 2, 15, 4, 19, 26, 27]第7次
[50, 48, 47, 46, 44, 38, 36, 27, 3, 2, 5, 4, 15, 19, 26]第8次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 2, 3, 4, 5, 15, 19]第9次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 19, 2, 3, 4, 5, 15]第10次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 19, 15, 2, 3, 4, 5]第11次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 19, 15, 5, 2, 3, 4]第12次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 19, 15, 5, 4, 2, 3]第13次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 19, 15, 5, 4, 3, 2]第14次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 19, 15, 5, 4, 3, 2]第15次
可以看出来,最后第15次,与14次的结果是一样的,所以不用循环15次。第1个值,只需要与后面的14个值进行比较。其实第二层循环j的值也可以少一次,自己慢慢体会吧。
优化后的代码:
"""
冒泡法排序
"""
#一个数字列表,用于排序
l = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]
for i in range(len(l)-1): #不必跟自己比较,只需要与自身后面的值比较。循环可以少1次,所以-1
for j in range(i+1,len(l)):# j应该i的下一位,所以i+1
if l[i] < l[j]: #如果当前值小于后面的值
l[i], l[j] = l[j], l[i] #当前值和和后的值做交换
print(f"{l}第{i+1}次") #查看每一次的结果
结果:
[50, 3, 38, 5, 44, 15, 36, 26, 27, 2, 46, 4, 19, 47, 48]第1次
[50, 48, 3, 5, 38, 15, 36, 26, 27, 2, 44, 4, 19, 46, 47]第2次
[50, 48, 47, 3, 5, 15, 36, 26, 27, 2, 38, 4, 19, 44, 46]第3次
[50, 48, 47, 46, 3, 5, 15, 26, 27, 2, 36, 4, 19, 38, 44]第4次
[50, 48, 47, 46, 44, 3, 5, 15, 26, 2, 27, 4, 19, 36, 38]第5次
[50, 48, 47, 46, 44, 38, 3, 5, 15, 2, 26, 4, 19, 27, 36]第6次
[50, 48, 47, 46, 44, 38, 36, 3, 5, 2, 15, 4, 19, 26, 27]第7次
[50, 48, 47, 46, 44, 38, 36, 27, 3, 2, 5, 4, 15, 19, 26]第8次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 2, 3, 4, 5, 15, 19]第9次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 19, 2, 3, 4, 5, 15]第10次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 19, 15, 2, 3, 4, 5]第11次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 19, 15, 5, 2, 3, 4]第12次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 19, 15, 5, 4, 2, 3]第13次
[50, 48, 47, 46, 44, 38, 36, 27, 26, 19, 15, 5, 4, 3, 2]第14次
看图片更加直观,感谢作者。
选择法排序: