排序方法(二)补

插入法排序还可以用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的时候要特殊对待

猜你喜欢

转载自www.cnblogs.com/AcodingDg/p/9094124.html
今日推荐