数据结构与算法: 希尔排序-python实现

# 希尔排序总体框架
# 1 依次给定gap值,将数组分割成若干子序列数组,子序列数组相邻元素在原数组中索引值是以gap大小递增的, 这样共有gap个子序列数组
# 2 将每一个子序列数组按照插入排序方式排序
# 3 不断缩小gap值,每次得到新的gap值时,按步骤1,2再次对数组进行排序
# 4 等到gap=1,排完序后,原数组必然有序
def shell_sort(arr):
    assert isinstance(arr, list)
    arr_length = len(arr)
    gap = arr_length // 2  # python 中整除是地板除法
    while gap >= 1:
        # 给定gap值,对各个子序列进行排序 
        gap_sort(arr, gap)
        gap = gap // 2

# 给定gap值,对各个子序列进行排序 
def gap_sort(arr, gap):
    i = 0
    while i < gap:
        # 对单个子序列用插入排序进行排序
        gap_insert_sort(arr, gap, i)
        i = i + 1


# 对一个子序列进行插入排序,该子序列的相邻元素在原数组中,索引值相差gap
def gap_insert_sort(arr, gap, start_index):
    arr_len = len(arr)
    insert_start_elem_index = start_index + gap
    cur_elem_index = insert_start_elem_index
    while cur_elem_index < arr_len:
        insert_elem(arr, gap, start_index, cur_elem_index)
        cur_elem_index = cur_elem_index + gap


def insert_elem(arr, gap, start_index, cur_elem_index):
    cur_elem = arr[cur_elem_index]
    compare_index = cur_elem_index - gap
    while compare_index >= start_index and cur_elem < arr[compare_index]:
        arr[compare_index + gap] = arr[compare_index]
        compare_index = compare_index - gap
    arr[compare_index + gap] = cur_elem

猜你喜欢

转载自blog.csdn.net/dinghua_xuexi/article/details/106905925