题目:利用for循环,完成a=[1,7,4,89,34,2]的冒泡排序(冒泡排序:小的排前面,大的排后面。)
第一种:可以看到每次排序的结果
a = [100,97,4,89,34,2]
n = 0
for n in range(0,5):
for i in range(0,len(a)-1):
if a[i] > a[i+1]:
a[i+1],a[i] = a[i],a[i+1]
# change = a[i]
# a[i] = a[i+1]
# a[i+1] = change
n += 1
print("第{}次排序结果:{}".format(n,a))
运行结果:
第1次排序结果:[97, 4, 89, 34, 2, 100]
第2次排序结果:[4, 89, 34, 2, 97, 100]
第3次排序结果:[4, 34, 2, 89, 97, 100]
第4次排序结果:[4, 2, 34, 89, 97, 100]
第5次排序结果:[2, 4, 34, 89, 97, 100]
第二种:代码简洁
a=[100,97,4,89,34,2]
for i in range(len(a)-1):
for j in range(len(a)-i-1):
if a[j] > a[j+1]:
a[j+1],a[j] = a[j],a[j+1]
print(a)
运行结果:[2, 4, 34, 89, 97, 100]
==================================================================================
尊重原创,若需转载请注明出处:https://www.cnblogs.com/lizhe860/
==================================================================================