defInsert_sort (alist):#from the second position, that is, the element labeled 1 starts to insert forward forIinchRange (1, Len (alist)):#starting from the first element I, if it is less than the previous one, swap position forJinchRange (I, 0, 1): ifALIST[J] < Alist[j-1]: alist[j], alist[j-1] = alist[j-1], Alist[j]Else: Breakalist= [54,26,93,17,77,31,44,55,20]insert_sort (alist)Print(alist)
- Optimal time complexity: O (n) (in ascending order, sequence already in ascending state)
- Worst time complexity: O (n2)
- Stability: Stable
Works by constructing an ordered sequence, for unsorted data, to scan from backward forward in the sorted sequence, to locate and insert the corresponding position. Insert sort on implementation, in the process of backward forward scanning, the ordered elements need to be shifted backwards and forwards, providing the insertion space for the newest elements.
Python Insert sort