希尔排序(Shell Sort)是插入排序的一种。也称缩小增量排序,比插入排序算法更高效
#!/usr/bin/python
# coding=utf-8
def shell_sort(a_list):
"""希尔排序"""
n = len(a_list)
gap = n // 2
while gap >= 1:
# 插入排序算法
for j in range(gap, n):
# 处理元素向前遍历,比较后并插入相应的位置
i = j
while i-gap >= 0:
if a_list[i] < a_list[i-gap]:
a_list[i], a_list[i-gap] = a_list[i-gap], a_list[i]
i -= gap
else:
break
# 每次缩短gap的间隔
gap //= 2
if __name__ == '__main__':
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print(a_list)
shell_sort(a_list)
print(a_list)
# 输出结果
排序前: [54, 26, 93, 17, 77, 31, 44, 55, 20]
排序后: [17, 20, 26, 31, 44, 54, 55, 77, 93]
"""
算法演示:
before_sorted gap i sorted
[54, 26, 93, 17, 77, 31, 44, 55, 20] -> 4 4 [54, 26, 93, 17, 77, 31, 44, 55, 20]
[54, 26, 93, 17, 77, 31, 44, 55, 20] -> 4 5 [54, 26, 93, 17, 77, 31, 44, 55, 20]
[54, 26, 93, 17, 77, 31, 44, 55, 20] -> 4 6 [54, 26, 44, 17, 77, 31, 93, 55, 20]
[54, 26, 44, 17, 77, 31, 93, 55, 20] -> 4 7 [54, 26, 44, 17, 77, 31, 93, 55, 20]
[54, 26, 44, 17, 77, 31, 93, 55, 20] -> 4 8 [20, 26, 44, 17, 54, 31, 93, 55, 77]
[20, 26, 44, 17, 54, 31, 93, 55, 77] -> 2 2 [20, 26, 44, 17, 54, 31, 93, 55, 77]
[20, 26, 44, 17, 54, 31, 93, 55, 77] -> 2 3 [20, 17, 44, 26, 54, 31, 93, 55, 77]
[20, 17, 44, 26, 54, 31, 93, 55, 77] -> 2 4 [20, 17, 44, 26, 54, 31, 93, 55, 77]
[20, 17, 44, 26, 54, 31, 93, 55, 77] -> 2 5 [20, 17, 44, 26, 54, 31, 93, 55, 77]
[20, 17, 44, 26, 54, 31, 93, 55, 77] -> 2 6 [20, 17, 44, 26, 54, 31, 93, 55, 77]
[20, 17, 44, 26, 54, 31, 93, 55, 77] -> 2 7 [20, 17, 44, 26, 54, 31, 93, 55, 77]
[20, 17, 44, 26, 54, 31, 93, 55, 77] -> 2 8 [20, 17, 44, 26, 54, 31, 77, 55, 93]
[20, 17, 44, 26, 54, 31, 77, 55, 93] -> 1 1 [17, 20, 44, 26, 54, 31, 77, 55, 93]
[17, 20, 44, 26, 54, 31, 77, 55, 93] -> 1 2 [17, 20, 44, 26, 54, 31, 77, 55, 93]
[17, 20, 44, 26, 54, 31, 77, 55, 93] -> 1 3 [17, 20, 26, 44, 54, 31, 77, 55, 93]
[17, 20, 44, 26, 54, 31, 77, 55, 93] -> 1 4 [17, 20, 26, 44, 54, 31, 77, 55, 93]
[17, 20, 44, 26, 54, 31, 77, 55, 93] -> 1 5 [17, 20, 26, 31, 44, 54, 77, 55, 93]
[17, 20, 26, 31, 44, 54, 77, 55, 93] -> 1 6 [17, 20, 26, 31, 44, 54, 77, 55, 93]
[17, 20, 26, 31, 44, 54, 77, 55, 93] -> 1 7 [17, 20, 26, 31, 44, 54, 55, 77, 93]
[17, 20, 26, 31, 44, 54, 77, 55, 93] -> 1 8 [17, 20, 26, 31, 44, 54, 55, 77, 93]
"""