Basic idea of inserting sort:
Each step inserts a record to be sorted by the size of its key value into the appropriate position in the previously sorted file until all is inserted.
Cases:
arr = [49,38,04,97,76,13,27,49,55,65], from the 2nd number as the key value, compares forward, as the previous number is large, is exchanged,
arr = [38,49,04,97,76,13,27,49,55,65], and then from the 3rd number as the key value, the forward comparison, the former large is exchanged,
arr = [38,04,49,97,76,13,27,49,55,65], then continue, arr = [04,38,49,97,76,13,27,49,55,65]
Note: In order to compare forward, because the previous array is ordered, so the current number is less than or equal to the key value, you can jump out of the forward comparison of the loop, the algorithm speed is significantly improved.
Code:
def insert_sort (lists): #插入排序 count = Len (lists) for I in range (1,count): #从第2个数起遍历 key = Lists[i] j = i-1 while J >= 0: if LISTS[J] > key: lists[j+1], lists[j] = lists[j], key else:break #当前一 If the number is less than or equal to key, jump out of loop J-= 1 return lists