直接插入排序法


 1 # 2.1.1 直接插入排序法
 2 # a=[50,30,65,59,2,36,42,5,9]
 3 class Solution:
 4     def insertSort(self, a):
 5         for i in range(1, len(a)):
 6             key = a[i]
 7             j = i - 1
 8             while j >= 0 and a[j] > key:
 9                 a[j + 1] = a[j]
10                 j -= 1
11             a[j + 1] = key
12         return a
13 
14 
15 c1 = Solution()
16 print(c1.insertSort([50, 30, 65, 59, 2, 36, 42, 5, 9]))

#排序结果: [2, 5, 9, 30, 36, 42, 50, 59, 65]