【数据结构算法】:Python实现希尔排序

动图展示

算法时间复杂度o(n1.3)

python

希尔排序的思路就是:
先把待排序的序列分成若干个子序列,并对这若干个子序列分别进行插入排序。这若个子序列的元素间隔是不断减小的,知道间隔为1(此时对序列进行排序就等同于插入排序了)。

def shellsort(arr):
    gaps = [5,3,1]
    #对于每一个gap都执行一次插入排序
    for gap in gaps:
        for i in range(gap,len(arr)):
            preIndex = i - gap
            curr = arr[i]
            while preIndex>=0 and arr[preIndex]>curr:
                arr[preIndex+gap] = arr[preIndex]
                preIndex -= gap
            arr[preIndex+gap] = curr
    return arr

if __name__ == "__main__":
    arr = [3,4,5,7,6,8,0,9,1,-1,-4]
    output = shellsort(arr)
    print output

猜你喜欢

转载自blog.csdn.net/qiu931110/article/details/81632668