排序算法 之 希尔排序ShellSort

来源:互联网 发布:java jlabel 链接 编辑:程序博客网 时间:2024/04/28 11:08

介绍

希尔排序,也称递减增量排序算法,实质是分组插入排序。由 Donald Shell 于1959年提出。希尔排序是非稳定排序算法。

希尔排序的基本思想是:将数组列在一个表中并对列分别进行插入排序,重复这过程,不过每次用更长的列(步长更长了,列数更少了)来进行。最后整个表就只有一列了。将数组转换至表是为了更好地理解这算法,算法本身还是使用数组进行排序。

例如,假设有这样一组数[ 13 14 94 33 82 25 59 94 65 23 45 27 73 25 39 10 ],如果我们以步长为5开始进行排序,我们可以通过将这列表放在有5列的表中来更好地描述算法,这样他们就应该看起来是这样:

13 14 94 33 8225 59 94 65 2345 27 73 25 3910

然后我们对每列进行排序:

10 14 73 25 2313 27 94 33 3925 59 94 65 8245

将上述四行数字,依序接在一起时我们得到:[ 10 14 73 25 23 13 27 94 33 39 25 59 94 65 82 45 ]。这时10已经移至正确位置了,然后再以3为步长进行排序:

10 14 7325 23 1327 94 3339 25 5994 65 8245

排序之后变为:

10 14 1325 23 3327 25 5939 65 7345 94 8294

最后以1步长进行排序(此时就是简单的插入排序了)。

这里写图片描述

这里写图片描述

代码

# -*- coding: utf-8 -*-"""Created on Tue Apr 26 17:08:17 2016@author: zang"""from matplotlib import pyplot as pltimport randomdef shellSort(ary):    n = len(ary)    gap = int(round(n/2))       #初始步长 , 用round四舍五入取整    while gap > 0 :        for i in range(gap,n):        #每一列进行插入排序 , 从gap 到 n-1            temp = ary[i]            j = i            while ( j >= gap and ary[j-gap] > temp ):    #插入排序                ary[j] = ary[j-gap]                j = j - gap            ary[j] = temp        gap = int(round(gap/2))                   #重新设置步长    return arydef plotScatter(inputList):    plt.scatter(range(len(inputList)),inputList)    plt.show()if __name__ == "__main__":    num_list = range(1000)    unsortedList = random.sample(num_list, 30)    print "unsortedList:"    plotScatter(unsortedList)    print unsortedList    sortedList = shellSort(unsortedList)    print "sortedList:"    plotScatter(sortedList)    print sortedList

测试

输入

[84, 378, 602, 966, 54, 98, 749, 51, 735, 883, 326, 580, 506, 572, 59, 183, 493, 337, 246, 421, 115, 149, 784, 529, 207, 574, 176, 614, 855, 121]

这里写图片描述

输出

[51, 54, 59, 84, 98, 115, 121, 149, 176, 183, 207, 246, 326, 337, 378, 421, 493, 506, 529, 572, 574, 580, 602, 614, 735, 749, 784, 855, 883, 966]

这里写图片描述

分析

情况 性能 Worst case performance: – Best case performance: n Average case performance: O(nlogn2) Worst case space complexity: O(1)

参考

  • http://wuchong.me/blog/2014/02/09/algorithm-sort-summary/
  • http://blog.jobbole.com/72850/
0 0
原创粉丝点击