[root@localhost ~]# cat bubble1.py
#!/usr/bin/python
a=[999, 1,3,58,9089,9, 7]
move = 0
for i, val1 in enumerate(a):
starter = i
for pointer, val2 in enumerate(a):
if pointer > starter and a[pointer] < a[starter]:
move += 1
print("before: "+str(a))
a[starter],a[pointer] = a[pointer], a[starter]
print("%s swaping %s(%s) <-> %s(%s)"%(move, starter+1,a[starter],pointer+1,a[pointer]))
print("%s swapped: "%move + str(a))
print("final: "+str(a))
print("times to swap: %s"%move)
[root@localhost ~]# cat bubble1.py
#!/usr/bin/python
a=[999, 1,3,58,9089,9, 7]
move = 0
for i, val1 in enumerate(a):
starter = i
for pointer, val2 in enumerate(a):
if pointer > starter and a[pointer] < a[starter]:
move += 1
print("before: "+str(a))
a[starter],a[pointer] = a[pointer], a[starter]
print("%s swaping %s(%s) <-> %s(%s)"%(move, starter+1,a[starter],pointer+1,a[pointer]))
print("%s swapped: "%move + str(a))
starter = pointer #起始位置后移
print("final: "+str(a))
print("times to swap: %s"%move)
改进后提升排序速度,减少一次交换