Insert Sort principle: It works by constructing an ordered sequence, for unsorted data, from a backward forward scan in a sorted sequence, to find the appropriate position and insert it.
Insert Sort Core: Assume that the first element is lined up, and then the elements are compared and moved forward from the back to the well-arranged parts.
Implementation tips:
A group of data is divided into two groups, which I call the ordered group and the group to be inserted respectively. Each time you remove an element from the group to be inserted, compare it with the elements of the ordered group, and find the appropriate location to insert the element into the ordered group. In this way, each time an element is inserted, the ordered group is incremented and the insertion group is reduced. Until the number of group elements to be inserted is 0. Of course, the insertion process involves the movement of elements.
For ease of ordering, we generally treat the first element of the data as an ordered group, and the others as the group to be inserted.
The following example illustrates this in ascending order:
Python code:
#Coding=utf-8" "Select sort: Idea: the insertion sort principle is very simple, and a group of data is divided into two groups, which I call the ordered group and the group to be inserted respectively. Each time you remove an element from the group to be inserted, compare it with the elements of the ordered group, and find the appropriate location to insert the element into the ordered group. In this way, each time an element is inserted, the ordered group is incremented and the insertion group is reduced. Until the number of group elements to be inserted is 0. Of course, the insertion process involves the movement of elements. Implementation tips: For ease of ordering, we generally consider the first element of the data as an ordered group, others are to be inserted into the group. Reference blog: http://blog.csdn.net/llzk_/article/details/51628574" "defInsertionsort (list): I=1#To Insert an element subscriptJ=0#the last element of the sequenceTemp=0#the intermediate variable is used to store the value of the element to be sorted forIinchRange (len (list)): J=i-1Temp=List[i] while(j>=0 andtemp<List[j]): List[j+1] =List[j] J= J-1Else: List[j+1]=Tempreturnlistlist= [2,1,4,2,4,2,4,2,1,4,3,5,1]Print "array sequence before sorting"Print "----------------------------------------"Printlistinsertionsort (list)Print "after sorting"PrintList
Execution Result:
Python insertion Sort