This article mainly introduces the implementation code of the python insertion sorting algorithm.
1. algorithm:
Set a set of keywords {K 1, K 2 ,..., K n}; at the beginning of sorting, K 1 is considered an ordered sequence. let K 2 insert the above-mentioned ordered sequence with a table length of 1 to make it an ordered sequence with a table length of 2; then, let K 3 insert the sequence of the preceding table length of 2 to make it an ordered sequence of the table length of 3. then, let K n insert the sequence of the preceding table length of n-1, obtain an ordered sequence with a table length of n.
2. Insert the sorting code in python
The code is as follows:
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
Result: [2, 3, 4, 21, 33, 44, 45, 67]
3. time complexity: O (n * n)