zoukankan      html  css  js  c++  java
  • 数据结构与算法(17)——谢尔排序

    • 谢尔排序

    以插入排序作为基础,插入排序在最好 情况为O(n),这种情况发生在列表已经是有序的情况下,实际上,列表越接近有序表,插入排序的比对次数越少。

    因此,谢尔排序则将插入排序分为固定间隔的很多子列表,每个子列表都进行插入排序。

     一般子列表的间隔从n/2开始。

    谢尔排序的实质是带间隔的插入排序。

    •  代码
    #谢尔排序是插入排序的一般情况
    def shellsubSort(alist):
        sublistcount = len(alist)//2
        while sublistcount > 0:
            for startposition in range(sublistcount):
                gapInsertSort(alist, startposition, sublistcount)
            print('After increments of size',sublistcount,'The lit is', alist)
            sublistcount = sublistcount // 2 #间隔缩小
    #插入排序
    def gapInsertSort(alist, start, gap):
        for i in range(start+gap, len(alist), gap):
            currentvalue = alist[i]
            position = i
    
            while position >= gap and alist[position-gap]>currentvalue:
                alist[position] = alist[position-gap]
                position = position -gap   #减去间隔
            alist[position] = currentvalue
    alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
    shellsubSort(alist)
    print(alist)
    • 性能分析

    谢尔排序相比插入排序可能并不会比其好,但由于没趟都使得列表更加接近有序,这个过程会减少很多原先需要的无效的比对。

    谢尔排序的时间复杂度介于o(n)~o(n^2)之间。约为o(n^3/2)

  • 相关阅读:
    洛谷 P1410 子序列(DP)
    LibreOJ #539. 「LibreOJ NOIP Round #1」旅游路线(倍增+二分)
    LibreOJ #541. 「LibreOJ NOIP Round #1」七曜圣贤(单调队列)
    浴谷八连测R6题解(收获颇丰.jpg)
    数论的一些小结论
    Fence9
    二模 (2) day1
    二模 (1) day2
    二模 (1) day1
    一些编码时的老错误
  • 原文地址:https://www.cnblogs.com/yeshengCqupt/p/13341053.html
Copyright © 2011-2022 走看看