Python 实现希尔排序算法

希尔排序(shell sort):

希尔排序(Shell Sort)是插入排序的一种。也称缩小增量排序,比插入排序算法更高效

  • 希尔排序算法如下:
    • 先指定间隔, 一般取一半, 分成两组 
    • 再将每组对应索引元素进行比较, 如果 元素i < 元素i-gap, 则交换位置
    • 再次指定间隔, 分成四组, 继续执行上一步元素比较操作, 此时增量gap减小一倍, 重复上述操作
    • 当增量减至1时,整个序列恰被分成一组,执行插入排序, 算法便终止
  • 时间复杂度:
    • 最优时间复杂度:根据步长序列的不同而不同
    • 最坏时间复杂度:O(n2)
    • 稳定性:不稳定
  • 代码实现如下:
#!/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]

"""

 

你可能感兴趣的:(Python)