有如下列表,要求从左到右顺序排序
li = [13,22,6,99,11]
实现方法:
li = [13,22,6,99,11] print "##########原始数字顺序################" print li print "#########开始第一次排序############3" for m in range(4): num1 = li[m] num2 = li[m+1] if num1>num2: tmp = li[m] li[m] = num2 li[m+1] = tmp print li print "##########第二次排序################" for m in range(3): num1 = li[m] num2 = li[m+1] if num1>num2: tmp = li[m] li[m] = num2 li[m+1] = tmp print li print "##########第三次排序################" for m in range(2): num1 = li[m] num2 = li[m+1] if num1>num2: tmp = li[m] li[m] = num2 li[m+1] = tmp print li print "##########第四次排序################" for m in range(1): num1 = li[m] num2 = li[m+1] if num1>num2: tmp = li[m] li[m] = num2 li[m+1] = tmp print li
输出结果:
##########原始数字顺序################ [13, 22, 6, 99, 11] #########开始第一次排序############3 [13, 6, 22, 11, 99] ##########第二次排序################ [6, 13, 11, 22, 99] ##########第三次排序################ [6, 11, 13, 22, 99]
将上述代码改写:
li = [13,22,6,99,11]print "##########原始数字顺序################"print liprint "#########开始第一次排序############3"for m in range(len(li)-1): num1 = li[m] num2 = li[m+1] if num1>num2: tmp = li[m] li[m] = num2 li[m+1] = tmpprint liprint "##########第二次排序################"for m in range(len(li)-2): num1 = li[m] num2 = li[m+1] if num1>num2: tmp = li[m] li[m] = num2 li[m+1] = tmpprint liprint "##########第三次排序################"for m in range(len(li)-3): num1 = li[m] num2 = li[m+1] if num1>num2: tmp = li[m] li[m] = num2 li[m+1] = tmpprint li print "##########第四次排序################"for m in range(len(li)-4): num1 = li[m] num2 = li[m+1] if num1>num2: tmp = li[m] li[m] = num2 li[m+1] = tmpprint li
输出结果:
##########原始数字顺序################[13, 22, 6, 99, 11]#########开始第一次排序############3[13, 6, 22, 11, 99]##########第二次排序################[6, 13, 11, 22, 99]##########第三次排序################[6, 11, 13, 22, 99]##########第四次排序################ [6, 11, 13, 22, 99]
从上述的红色部分的4-3-2-1可以发现这个数字是渐进增加,也是一个循环数字,这样可以用一个变量n来代替,再进行改写:
for n in range(1,len(li)): print n
这样输出的n结果为:
1,2,3,4
以上代码可以改写为:
li = [13,22,6,99,11] for n in range(1,len(li)):#1,2,3,4 for m in range(len(li)-n):#4,3,2,1 num1 = li[m] #将li[m]的值赋给num1 num2 = li[m+1] #将li[m+1]的值赋给num2 if num1>num2: #如果num1大于num2,那么将较大的放在右边 tmp = li[m] #将li[m]的值赋给tmp li[m] = num2 #将num2的值赋给li[m] li[m+1] = tmp #将tmp的值,也就是之前li[m]的值赋给li[m+1] print li
输出结果为:
[6, 11, 13, 22, 99]
注:冒泡算法可用于列表类的文章或者邮件按照时间排序