Problem description
A set of randomly arranged numbers is re-arranged in small to large order.
Insert algorithm
Each time a number is taken from the array, compared to the existing number and inserted in the appropriate position.
So repeat, each time you can keep the existing numbers in order, until the numbers are finished, the sorting is successful.
It's a lot like a poker-card situation,
First condition: Keep the hands on the cards in the correct order
The second condition: each time the new cards are caught in order to insert the hand in the middle of the card.
Ensure that these two are not changed, then no matter how many cards are caught, the cards in the final hand are arranged in order.
Python implementations:
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] &l t;= 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