选择排序
算法流程:
首先在未排序序列中找到最小(大)元素,存放到起始位置。
再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
重复第二步,直到所有元素均排序完毕。
代码实现:
1 def select_sort(li): 2 for i in range(len(li)-1): # i是第几趟 3 min_loc = i 4 # 第二个for循环寻找最小数的位置 5 for j in range(i+1, len(li)): 6 if li[j] < li[min_loc]: 7 min_loc = j 8 if i != min_loc: 9 li[i], li[min_loc] = li[min_loc], li[i] 10 print(li) 11 12 li = [3,4,2,1,5,10,2,6,8,7,9] 13 select_sort(li)
执行结果:
[1, 4, 2, 3, 5, 10, 2, 6, 8, 7, 9]
[1, 2, 4, 3, 5, 10, 2, 6, 8, 7, 9]
[1, 2, 2, 3, 5, 10, 4, 6, 8, 7, 9]
[1, 2, 2, 3, 5, 10, 4, 6, 8, 7, 9]
[1, 2, 2, 3, 4, 10, 5, 6, 8, 7, 9]
[1, 2, 2, 3, 4, 5, 10, 6, 8, 7, 9]
[1, 2, 2, 3, 4, 5, 6, 10, 8, 7, 9]
[1, 2, 2, 3, 4, 5, 6, 7, 8, 10, 9]
[1, 2, 2, 3, 4, 5, 6, 7, 8, 10, 9]
[1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10]