码迷,mamicode.com
首页 > 编程语言 > 详细

排序方法(二)补

时间:2018-05-26 21:19:04      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:ted   style   比较   ==   doc   span   pytho   lse   name   

插入法排序还可以用python的切片功能和递归的思路来实现

‘‘‘
From smallest to largest
‘‘‘
def insert_sorted(list_of_nb):
    ‘‘‘
    >>> insert_sorted([5,4,56,6,7,85,35])
    [4, 5, 6, 7, 35, 56, 85]
    ‘‘‘
    if not list_of_nb:
        return
    return _insert_sorted(list_of_nb)

def _insert_sorted(list_of_nb):
    if len(list_of_nb) == 1:
        return list_of_nb
    L1 = _insert_sorted(list_of_nb[1:])
    if list_of_nb[0] <= L1[0]:
        return [list_of_nb[0]] + L1
    elif list_of_nb[0] >= L1[-1]:
        return L1 + [list_of_nb[0]]
    else:
        if len(L1) == 2:
            return [L1[0]] + [list_of_nb[0]] + [L1[-1]]
        i = 1
        while i < len(L1):
            if list_of_nb[0] < L1[i]:
                return L1[:i] + [list_of_nb[0]] + L1[i:]
            i += 1

if __name__ == __main__:
    import doctest
    doctest.testmod()

比较tricky的地方是L1长度为2的时候要特殊对待

排序方法(二)补

标签:ted   style   比较   ==   doc   span   pytho   lse   name   

原文地址:https://www.cnblogs.com/AcodingDg/p/9094124.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!