Python inserts the sort algorithm implementation code
- 2020-04-02 13:11:42
- OfStack
1. The algorithm:
Set of keywords {K 1, K 2... , K n}; Sorting starts with the idea that K one is an ordered sequence; Let K 2 insert the ordered sequence of table 1 to make it an ordered sequence of table 2; Then, let K 3 insert the ordered sequence with the length of 2 to make it an ordered sequence with the length of 3. Finally, let K and n insert the ordered sequence with the length of the above table as n-1, and get an ordered sequence with the length of the table as n.
Python inserts sort code
def insertion_sort(list2):
for i in range(1, len(list2)):
save = list2[i]
j = i
while j > 0 and list2[j - 1] > save:
list2[j] = list2[j - 1]
j -= 1
list2[j] = save
Results: [2, 3, 4, 21, 33, 44, 45, 67]
3. Time complexity: O(n*n)