冒泡排序


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#-*- coding=utf-8 -*-

data = [5, 4, 3, 2, 1]
print data

def sort():
for i in range(0, len(data)):
for j in range(i, 0, -1):
pre = j - 1
if data[j] < data[pre]:
tmp = data[pre]
data[pre] = data[j]
data[j] = tmp
print str(data[pre]) + " compore " + str(data[j]) + " -> " + str(data)

sort()

结果为

1
2
3
4
5
6
7
8
9
10
11
[5, 4, 3, 2, 1]
4 compore 5 -> [4, 5, 3, 2, 1]
3 compore 5 -> [4, 3, 5, 2, 1]
3 compore 4 -> [3, 4, 5, 2, 1]
2 compore 5 -> [3, 4, 2, 5, 1]
2 compore 4 -> [3, 2, 4, 5, 1]
2 compore 3 -> [2, 3, 4, 5, 1]
1 compore 5 -> [2, 3, 4, 1, 5]
1 compore 4 -> [2, 3, 1, 4, 5]
1 compore 3 -> [2, 1, 3, 4, 5]
1 compore 2 -> [1, 2, 3, 4, 5]