1.介紹:插入式排序?qū)儆趦?nèi)部排序法,是對于欲排序的元素以插入的方式找尋該元素的適當(dāng)位置瓣戚,以達(dá)到排序的目的端圈。
2.思想:插入排序(InsertionSorting)的基本思想是:把n個待排序的元素看成為一個有序表和一個無序表,開始時有序表中只包含一個元素子库,無序表中包含有n-1個元素舱权,排序過程中每次從無序表中取出第一個元素,把它的排序碼依次與有序表元素的排序碼進(jìn)行比較仑嗅,將它插入到有序表中的適當(dāng)位置宴倍,使之成為新的有序表张症。
3.動圖來源:https://www.toutiao.com/a6593273307280179715/?iid=6593273307280179715&wid=1621761486436
插入排序
4.代碼實(shí)現(xiàn)
import random
import time
def sorted(sortlist):
for i in range(len(sortlist)-1): #curIndex表示操作的書即把哪個數(shù)插入到列表里面去
curIndex = i + 1
curValue = sortlist[curIndex] #記錄這個值后面就不會找不到
while (curIndex > 0 and curValue < sortlist[curIndex-1]):
#curIndex > 0保證不越界,curValue < sortlist[curIndex-1]則是判斷往哪個位置插入
curIndex = curIndex - 1
sortlist[curIndex+1] = sortlist[curIndex]
sortlist[curIndex] = curValue
# print(sortlist)
l = []
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
for i in range(80000):
l.append(int(random.random()*100000000))
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
sorted(l)
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))