1. 程式人生 > >用python實現希爾排序(shell_sort)

用python實現希爾排序(shell_sort)

def shell_sort(a):
    n = len(a)
    gap = n >> 1  # gap是長度的一半
    while gap > 0:
        for i in range(gap, n):
            for j in range(i, 0, -gap):
                if a[j] < a[j - gap]:
                    a[j], a[j - gap] = a[j - gap], a[j]
                else:
                    break
gap >>= 1 # gap每次減半 if __name__ == "__main__": a = [10, 4, 3, 1, 6, 20, 30, 1, 40, 30, 20] print(a) shell_sort(a) print(a)