Look at so many insert sorts, explain this method.
There are several steps:
1 think the previous sequence has been sorted, that is, in order from small to large, the largest in the last side
2 Save the next number of a[i] into a variable, a[i] = data. That is, I dug a hole in this position.
3 starting at the end of the sorted array a[j], starting with the maximum value of a[j], data is less honest and wants to traverse the well-arranged sections by J, finding a larger number than itself, and then letting them pits in turn. If data is large, then the loop ends, and data returns to the original pit, and if data is small, a[j] moves back one fill the pit and then empties its position into the new pit: a[j+1] = a[j]. Each round is compared j--until J < 0, or data is returned to the pit.
4 After the end of the loop, the value of a[j] is less than the new value, then the value at A[j+1] is the new value data: a[j+1] = data.
The entire code is as follows:
def insert_sort (a): for i in range (1,len (a)): data = a[i] #先挖一个坑 j = i - 1 while j >= 0 and a[j] > data: #data看是不是比自己大 a[j+1] = a[j] #是的话, let that value back pits, a[j+1] will always be the data dug pit j = j-1 # Then the next a[j+1] = data #比较结束了, data goes back to the pit he just dug return A
Python Insert Sort