算法-希尔排序


希尔排序是不稳定排序的算法,希尔排序是在插入的排序上面进行了优化。

def shell_sort(a):
    step = len(a)//2
    while step >= 1:
        for i in range(step, len(a)):
            while i - step >= 0 and a[i] < a[i-step]:
                a[i], a[i-step] = a[i-step], a[i]
                i = i - step
        step = step//2


a = [1, 44, 2, -1, 23, 4, 5, 3, 3, -34, 456, 34, 22]

print(shell_sort(a))


结果:
[-34, -1, 1, 2, 3, 3, 4, 5, 22, 23, 34, 44, 456]