1 #冒泡排序 2 l = [1,3,5,2,3,6,7,9,0,2,12,34,23,98,39] 3 for i in range(len(l)-1):#控制总共需要多少趟 4 for j in range(len(l)-1-i):#这个循环是控制交换的次数 5 if l[j] > l[j+1]: 6 l[j],l[j+1] = l[j+1],l[j] 7 print(l)
2.二维数组冒泡排序
1 run_scores = {} 2 f = open(‘数据.txt‘,encoding=‘utf-8‘) 3 for userinfo in f: 4 temp1 = userinfo.split()#用空格分割,将名字和跑步公里数分割 5 run_scores[temp1[1]] = float(temp1[2])#将文件中的内容放入字典中 6 f.close()#关闭文件 7 print(run_scores) 8 9 items = list(run_scores.items()) 10 for i in range(len(items)-1):#控制总共需要多少趟 11 for j in range(len(items)-1-i):#这个循环是控制交换的次数 12 if items[j][-1] < items[j+1][-1]: 13 items[j],items[j+1] = items[j+1],items[j] 14 print(items) 15 count = 1 16 for name,km in items: 17 print(‘%s. %s %s‘%(count,name,km)) 18 count += 1
原文:https://www.cnblogs.com/cjxxl1213/p/12814551.html