用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)

你可能感兴趣的:(算法,python)