This article mainly introduces the simple analysis and code example of using the Insertion sorting algorithm in Python. The average time complexity of the insertion algorithm is O (n ^ 2). For more information, see
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
For more details about the simple analysis and sample code of the inserted sorting algorithm in Python, please follow the PHP Chinese network!