Skip to content

Commit 7df50fb

Browse files
committed
learn shell_sort
1 parent 993df1a commit 7df50fb

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed
Loading

sorts/shell_sort/readme.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# 希尔排序
2+
3+
## 概念
4+
5+
希尔排序(shell sort)这个排序方法又称为缩小增量排序。
6+
该方法的基本思想是:设待排序元素序列有`n`个元素,首先取一个整数增量(increment)<小于n>作为间隔将全部元素分为increment个子序列,所有距离为increment的元素放在同一个子序列中,在每一个子序列中分别实行直接插入排序。
7+
然后缩小间隔increment,重复上述子序列划分和排序工作。直到最后取increment=1,将所有元素放在同一个子序列中排序为止。
8+
由于开始时,increment的取值较大,每个子序列中的元素较少,排序速度较快,到排序后期increment取值逐渐变小,子序列中元素个数逐渐增多,但由于前面工作的基础,大多数元素已经基本有序,所以排序速度仍然很快。
9+
10+
## 图示
11+
12+
![希尔排序](./img/Sorting_shellsort_anim.gif)
13+
14+
## 复杂度
15+
16+
希尔排序是非稳定排序算法,该排序算法复杂度与步长密切相关。
17+
18+
| 步长序列 | 最坏情况下复杂度 |
19+
| -------- | ---------------- |
20+
| n/2^i | O(n^2) |
21+
| 2^k -1 | O(n^(3/2)) |
22+
| 2^i3^j | O(n log^2 n) |
23+
24+
## 参考阅读
25+
26+
[理解希尔排序的排序过程](https://blog.csdn.net/weixin_37818081/article/details/79202115)

sorts/shell_sort/shell_sort.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# Created by imoyao at 2019/5/13 18:33
4+
5+
import pathlib
6+
import sys
7+
8+
util_p = pathlib.Path('../..').resolve()
9+
10+
sys.path.append(str(util_p))
11+
from util import utils
12+
13+
14+
def shell_sort(unsorted_collection):
15+
"""
16+
希尔排序
17+
它以插入排序为基础,将原来要排序的列表划分为一些子列表,再对每一个子列表执行插入排序,从而实现对插入排序性能的改进。
18+
划分子列的特定方法是希尔排序的关键。我们并不是将原始列表分成含有连续元素的子列,而是确定一个划分列表的增量'i',
19+
这个i更准确地说,是划分的间隔。然后把每间隔为 i 的所有元素选出来组成子列表。
20+
:param unsorted_collection:待排序序列
21+
:return:排序后序列
22+
"""
23+
gaps = [701, 301, 132, 57, 23, 10, 4, 1] # 进行分割的步长列表
24+
for gap in gaps:
25+
i = gap
26+
# ----------------------此处为插入排序实现
27+
while i < len(unsorted_collection):
28+
temp = unsorted_collection[i]
29+
j = i
30+
while j >= gap and unsorted_collection[j-gap] > temp:
31+
unsorted_collection[j] = unsorted_collection[j-gap]
32+
j -= gap
33+
# -----------------
34+
unsorted_collection[j] = temp
35+
i += 1
36+
return unsorted_collection
37+
38+
39+
if __name__ == '__main__':
40+
unsorted_li = utils.rand_list(100)
41+
print('Before sorted:', unsorted_li)
42+
print('After sorted:', shell_sort(unsorted_li))

0 commit comments

Comments
 (0)