In an unordered sequence, build the subsequence until all rows are complete
Insert the number of rows to be sorted in the appropriate position
Add Sentinel, place the value to compare, and compare to sorted sequence to find the Fit insertion point
defInster_sort (*args): Lst1=list (args) Nums= [0]+lst1## #增加哨兵Length =Len (nums) Count_swap= 0## #记录交换次数Count_iter = 0## #记录循环次数 forIinchRange (2, Length): Nums[0]=Nums[i] J= I-1Count_iter+=1 whileTrue:ifNums[0] <Nums[j]: nums[j+1] = Nums[j]##大数后移Count_swap +=1Else: Nums[j+1] = nums[0]##定位 BreakJ-= 1Print(Nums,count_swap,count_iter)
Inster_sort (*[9,8,7,6,5,4,3,2,1])
[1, 1, 2, 3, 4, 5, 6, 7, 8, 9] 36 8
Inster_sort (*[1,9,8,5,6,7,4,3,2])
[2, 1, 2, 3, 4, 5, 6, 7, 8, 9] 25 8
Inster_sort (*[1,1,1,1,1,1,1,1,1])
[9, 1, 2, 3, 4, 5, 6, 7, 8, 9] 0 8
Inster_sort (*[1,1,1,1,1,1,1,1,2])
[2, 1, 1, 1, 1, 1, 1, 1, 1, 2] 0 8
For 9 numbers, it's best to compare 36 times, swap 0 times
Worst case, compare 36 times, swap 36 times.
(n-1)! * (n-1)!
Time complexity O (n)
Direct Insert Sort