先学习之前未完成的冒泡算法
li = [13,22,6,99,11]
从小到大
从第一个数字比较把大的往后移位
for m in range(4):
num1 = li[m]
num2 = li[m+1]
if num1 > num2:
temp = li[m]
li[m] = num2
li[m+1] = temp
print li
循环四次就把最大数放到列表的最后
for m in range(3):
num1 = li[m]
num2 = li[m+1]
if num1 > num2:
temp = li[m]
li[m] = num2
li[m+1] = temp
以此类推写成以下代码
vim day4-1.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
li = [13,22,6,99,11] for m in range(4): #循环 num1 = li[m] num2 = li[m+1] if num1 > num2: #前一个数字和后一个对比如果前面数字大与后面的对调 temp = num1 li[m] = num2 li[m+1] = temp print li for m in range(3): num1 = li[m] num2 = li[m+1] if num1 > num2: temp = num1 li[m] = num2 li[m+1] = temp print li for m in range(2): num1 = li[m] num2 = li[m+1] if num1 > num2: temp = num1 li[m] = num2 li[m+1] = temp print li for m in range(1): num1 = li[m] num2 = li[m+1] if num1 > num2: temp = num1 li[m] = num2 li[m+1] = temp print li #多次循环得到排序结果
[[email protected] scripts]# python day4-1.py
[13, 6, 22, 11, 99]
[6, 13, 11, 22, 99]
[6, 11, 13, 22, 99]
[6, 11, 13, 22, 99]
这样的循环很繁琐,假如不知道列表的长度更加麻烦需要多次循环
vim day4-2.py
#!/usr/bin/python # -*- coding:utf-8 -*- li = [13,22,6,99,11] for n in range(1,len(li)-1): #外层循环1,2,3,4 for m in range(len(li)-n): #内层循环4,3,2,1 num1 = li[m] num2 = li[m+1] if num1 > num2: temp = li[m] li[m] = li[m+1] li[m+1] = temp print li
运行结果的一样的
[[email protected] scripts]# python day4-2.py
[6, 11, 13, 22, 99]
时间: 2024-10-29 04:47:59