Simple Analysis and code example using the insert Sorting Algorithm in Python, python example
Problem description
Sorts random numbers in ascending order.
Insert Algorithm
Take a number from the array each time, compare it with the existing number, and insert the appropriate position.
In this case, the existing numbers can be sorted in order each time until the numbers are obtained, that is, they are sorted successfully.
This is very similar to card capturing during cards,
First condition: the order of cards on hand is correct.
The second condition: each time a new card is caught, it is inserted in the middle of the card in order.
To ensure that the two cards remain unchanged, no matter how many cards are captured, the cards at the end are arranged in order.
Python implementation:
Def insertion_sort (n): if len (n) = 1: return n B = insertion_sort (n [1:]) m = len (B) for I in range (m): if n [0] <= B [I]: return B [: I] + [n [0] + B [I:] return B + [n [0]
Another version:
Def insertion_sort (lst): if len (lst) = 1: return lst for I in xrange (1, len (lst )): temp = lst [I] j = I-1 while j> = 0 and temp <lst [j]: lst [j + 1] = lst [j] j-= 1 lst [j + 1] = temp return lst