选择排序:
思想:每次选择出最小的值依次放到最前面
代码:
1 a = [9,1,22,31,45,3,6,2,11]
3 for i in range(len(a)-1): 4 index = i #index标记最小的 值 假设第一个是最小的值 5 for j in range(i+1,len(a)): 6 if a[index] > a[j]: 7 index = j #index 一直指向最小的值 8 a[i],a[index] = a[index],a[i] #让a[index] 与 第[i]个值 互换 ,达到排序 9 print(a)
输出结果:[1, 2, 3, 6, 9, 11, 22, 31, 45]
过程:
[9, 1, 22, 31, 45, 3, 6, 2, 11]
[1, 9, 22, 31, 45, 3, 6, 2, 11]
[1, 2, 22, 31, 45, 3, 6, 9, 11]
[1, 2, 3, 31, 45, 22, 6, 9, 11]
[1, 2, 3, 6, 45, 22, 31, 9, 11]
[1, 2, 3, 6, 9, 22, 31, 45, 11]
[1, 2, 3, 6, 9, 11, 31, 45, 22]
[1, 2, 3, 6, 9, 11, 22, 45, 31]
[1, 2, 3, 6, 9, 11, 22, 31, 45]