插入排序

def insertionSort(arr):
   for i in range(len(arr)):
       preIndex = i-1
       current = arr[i]
       while preIndex >= 0 and arr[preIndex] > current:
           arr[preIndex+1] = arr[preIndex]
           preIndex-=1
       arr[preIndex+1] = current
   return arr


  1. 将第一待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列。

  2. 从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。(如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面。)

posted @ 2021-05-10 16:22  小僧回头啦  阅读(17)  评论(0编辑  收藏  举报