选择排序算法简单理解为:遍历一个数组,从索引为0开始和后面的索引的值对比,找到最小的,和其掉换位置,以此类推。

代码展示:
# coding:utf-8 import random # Get min value function def get_min(arg): result
= arg[0] for i in range(len(arg)): if result > arg[i]: result = arg[i] return
result # Select sort function come true def select_sort(arr): for i in
range(len(arr)): min_value = get_min(arr[i:]) if arr[i] > min_value:
arr[arr.index(min_value)] = arr[i] arr[i] = min_value print("遍历过程中:", arr)
return arr if __name__ == '__main__': arr_list = [each for each in range(20)]
random.shuffle(arr_list) print("生成随机数组:", arr_list) select_sort(arr_list)
print("排序后数组:", arr_list)
参考结果:

生成随机数组: [16, 9, 15, 19, 6, 7, 10, 18, 12, 3, 14, 11, 13, 17, 8, 5, 1, 0, 2, 4]
遍历过程中: [0, 9, 15, 19, 6, 7, 10, 18, 12, 3, 14, 11, 13, 17, 8, 5, 1, 16, 2, 4]
遍历过程中: [0, 1, 15, 19, 6, 7, 10, 18, 12, 3, 14, 11, 13, 17, 8, 5, 9, 16, 2, 4]
遍历过程中: [0, 1, 2, 19, 6, 7, 10, 18, 12, 3, 14, 11, 13, 17, 8, 5, 9, 16, 15, 4]
遍历过程中: [0, 1, 2, 3, 6, 7, 10, 18, 12, 19, 14, 11, 13, 17, 8, 5, 9, 16, 15, 4]
遍历过程中: [0, 1, 2, 3, 4, 7, 10, 18, 12, 19, 14, 11, 13, 17, 8, 5, 9, 16, 15, 6]
遍历过程中: [0, 1, 2, 3, 4, 5, 10, 18, 12, 19, 14, 11, 13, 17, 8, 7, 9, 16, 15, 6]
遍历过程中: [0, 1, 2, 3, 4, 5, 6, 18, 12, 19, 14, 11, 13, 17, 8, 7, 9, 16, 15, 10]
遍历过程中: [0, 1, 2, 3, 4, 5, 6, 7, 12, 19, 14, 11, 13, 17, 8, 18, 9, 16, 15, 10]
遍历过程中: [0, 1, 2, 3, 4, 5, 6, 7, 8, 19, 14, 11, 13, 17, 12, 18, 9, 16, 15, 10]
遍历过程中: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 14, 11, 13, 17, 12, 18, 19, 16, 15, 10]
遍历过程中: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 12, 18, 19, 16, 15, 14]
遍历过程中: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 17, 13, 18, 19, 16, 15, 14]
遍历过程中: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 17, 18, 19, 16, 15, 14]
遍历过程中: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 18, 19, 16, 15, 17]
遍历过程中: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 19, 16, 18, 17]
遍历过程中: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 18, 17]
遍历过程中: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
排序后数组: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

算法的思路来自马老师在B站(https://www.bilibili.com/video/av46774569?t=58
<https://www.bilibili.com/video/av46774569?t=58>)的教学视频,感谢分享。

 

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:637538335
关注微信