冒泡排序:
思路:
先找到最大值放到最右边:
#encoding=utf-8
a=[1,9,2,8,3,6,4]
print "a before change:",a
for i in range(len(a)-1):
if a[i] > a[i+1]:
a[i],a[i+1] = a[i+1],a[i]
print "a after change:",a
结果:
D:\>python test.py
a before change: [1, 9, 2, 8, 3, 6, 4]
a after change: [1, 2, 8, 3, 6, 4, 9]
找到最大值了,第二步找到次大值放到倒数第二个位置
#encoding=utf-8
a= [1, 2, 8, 3, 6, 4, 9]
for i in range(len(a)-1-1):
if a[i] > a[i+1]:
a[i],a[i+1] = a[i+1],a[i]
print "a after change:",a
结果:
D:\>python test.py
a before change: [1, 2, 8, 3, 6, 4, 9]
a after change: [1, 2, 3, 6, 4, 8, 9]
找到倒数第二大的值了
第三步找到倒数第三大的数放到倒数第三个位置
a=[1, 2, 3, 6, 4, 8, 9]
print "a before change:",a
for i in range(len(a)-1-1-1):
if a[i] > a[i+1]:
a[i],a[i+1] = a[i+1],a[i]
print "a after change:",a
结果:
D:\>python test.py
a before change: [1, 2, 3, 6, 4, 8, 9]
a after change: [1, 2, 3, 4, 6, 8, 9]
依次类推,最后可以把整个列表排好序
从整体的过程来看,每次循环做的事情基本一样,从左到右依次用当前位置的数和
后边的数做比较,如果前边的数大,就把两个数换位置,循环结束后可以得到所循环的树中最大的数
每一次循环不一样的是循环所遍历数据长度都比上一次少一个,一共需要循环的次数是列表a的长度,那么把这六次循环写到一起就可以变成两层循环
外边的循环控制循环的次数即6次,i的变化值是0,1,2,3,4,5,即range(len(a)-1)
里边的循环控制每次循环的长度,每次长度减少1,j变化值是6次,5次,4次,3次,2次,1次,即每次为range(len(a)-i-1)次
循环每次做的事情不动改变
即:
#encoding=utf-8
a=[1,9,2,8,3,6,4]
print "a before change:",a
for i in range(len(a)-1):
for j in range(len(a)-i-1):
if a[j] > a[j+1]:
a[j],a[j+1] = a[j+1],a[j]
print "a after change:",a
结果:
D:\>python test.py
a before change: [1, 9, 2, 8, 3, 6, 4]
a after change: [1, 2, 3, 4, 6, 8, 9]
原文地址:https://www.cnblogs.com/xiaxiaoxu/p/10193279.html