Python 希尔排序实现的算法?
参考答案:
希尔排序(Shell Sort)是插入排序的一种更高效的改进版本,也称为缩小增量排序。其基本思想是:先将整个待排序的记录序列分割成为若干子序列(由相隔某个“增量”的记录组成的)分别进行直接插入排序,然后依次缩减增量再进行排序,待整个序列中的记录"基本有序"时,再对全体记录进行依次直接插入排序。
以下是一个简单的 Python 实现:
def shell_sort(arr):
# Start with a big gap, then reduce the gap
n = len(arr)
gap = n // 2
# Do a gapped insertion sort for this gap size.
# The first gap elements a[0..gap-1] are already in gapped order
# keep adding one more element until the entire array is gap sorted
while gap > 0:
for i in range(gap, n):
# add a[i] to the elements that have been gap sorted
# save a[i] in temp and make a hole at position i
temp = arr[i]
# shift earlier gap-sorted elements up until the correct location for a[i] is found
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
# put temp (the original a[i]) in its correct location
arr[j] = temp
gap //= 2
# test the function
arr = [12, 34, 54, 2, 3]
shell_sort(arr)
print("Sorted array is:", arr)
在这个代码中,我们首先设定一个大的间隔(gap),然后对数组进行间隔排序。在每次迭代中,我们都会减小间隔的大小,直到间隔为 1。当间隔为 1 时,整个数组就已经接近有序,这时我们再进行一次直接插入排序,就能得到完全有序的数组。