失意的多啦

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

【十九题】插入排序

1、插入排序:最优为O(n),最坏为O(n^2),平均O(n^2)
(1)始终定义第一个元素为有序的,将剩余元素逐个插入到这个有序列中。
(2)插入过程中,将需要插入的元素与有序列中的元素逐个比较,插入到适当位置

 

def InserSort(lists):
    """
    :fuction:插入排序
    :param lists:[3,1,5,4,8,7,9,0]
    :return:[0, 1, 3, 4, 5, 7, 8, 9]
    """
    Count = len(lists)
    for i in range(1,Count):
        key = lists[i]
        index = i
        while index > 0 and lists[index-1] > key:
            lists[index] = lists[index-1]
            index -= 1
        lists[index] = key
    return lists
View Code

 

 

posted on 2019-11-28 20:23  失意的多啦  阅读(85)  评论(0)    收藏  举报