1. 程式人生 > >排序方法(二)補

排序方法(二)補

import __name__ () def col == doctest AS all

插入法排序還可以用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的時候要特殊對待

排序方法(二)補