程序员须掌握的数据结构:选择排序python代码实现

2018-10-3110:09:20数据结构与算法Comments2,007 views字数 604阅读模式

选择排序,时间复杂度O(n^2),比较次数与冒泡排序相同,交换次数小于冒泡排序。 选择排序6行。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/7594.html

# 源码: https://github.com/SpikeKing/data_structure_with_python
def selection_sort(alist):
    """
    选择排序,即选择最大值再交换
    1. 依然是2次遍历,第1次反序,第2次正序,注意起始为1,末尾+1;
    2. max_loc存储最大值,默认第0位;
    3. 当loc的值大于max_loc的值时,max_loc重新赋值;
    4. 交换loc和max_loc
    5. 6行
    :param alist: 待排序alist
    :return: None
    """
    for p_num in range(len(alist) - 1, 0, -1):
        max_loc = 0
        for i in range(1, p_num + 1):
            if alist[i] > alist[max_loc]:
                max_loc = i
        alist[p_num], alist[max_loc] = alist[max_loc], alist[p_num]


def tes_of_selection_sort():
    alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
    selection_sort(alist)
    print(alist)


if __name__ == '__main__':
    tes_of_selection_sort()

作者:SpikeKing
来源:掘金文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/7594.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/suanfa/7594.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定