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

2018-10-3110:10:18数据结构与算法Comments1,603 views字数 551阅读模式

插入排序,时间复杂度O(n^2),用移位代替交换,移位操作的时间大约是交换时间的1/3。插入排序7行。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/7595.html

# 源码: https://github.com/SpikeKing/data_structure_with_python
def insert_sort(alist):
    """
    插入排序,子序列逐渐有序
    1. 遍历列表,存储当前值cur_val,设置游标pos
    2. 游标大于0和游标的值大于当前值,则移位,同时游标减1;
    3. 将当前值赋予游标的终止位置;
    4. 7行
    :param alist: 待排序alist
    :return: None
    """
    for i in range(1, len(alist)):
        cur_val = alist[i]
        pos = i  # 游标
        while pos > 0 and alist[pos - 1] > cur_val:
            alist[pos] = alist[pos - 1]
            pos -= 1
        alist[pos] = cur_val  # 最后游标的位置


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


if __name__ == '__main__':
    test_of_insert_sort()
复制代码

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

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

Comment

匿名网友 填写信息

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

确定