1 import random 2 import time 3 4 # 插入排序 5 def insertion_sort(arr, step): 6 for i in range(step, len(arr)): 7 for j in range(i, step - 1, -step): 8 if arr[j] < arr[j-step]: 9 arr[j], arr[j-step] = arr[j-step], arr[j] 10 else: 11 break 12 13 # 希尔排序:插入排序算法的优化算法 14 def shell_sort(arr): 15 length = len(arr) 16 step = 1 17 18 while step < length // 3: 19 step = 3 * step + 1 20 21 while step >= 1: 22 insertion_sort(arr, step) 23 step = step // 3 24 25 26 if __name__ == '__main__': 27 arr = [random.randint(0, 1000000) for _ in range(5000)] 28 print('待排序数组大小:', len(arr)) 29 start = time.time() 30 shell_sort(arr) 31 end = time.time() 32 print('用时:', end - start)