1 import random 2 3 def insert_sort(nums): 4 # 排序趟数 5 for i in range(1, len(nums)): 6 current = nums[i] 7 pre_index = i - 1 8 while pre_index >= 0 and nums[pre_index] > current: 9 nums[pre_index+1] = nums[pre_index] 10 pre_index -= 1 11 nums[pre_index+1] = current 12 return nums 13 14 15 def test_arr(count, limit): 16 arr = [] 17 for i in range(count): 18 arr.append(random.randint(1, limit)) 19 return arr 20 21 22 if __name__ == '__main__': 23 arr = test_arr(10, 100) 24 print('插入排序前:') 25 print(arr) 26 insert_sort(arr) 27 print('插入排序后:') 28 print(arr)