插入排序相当于将列表数据分成左右两边,就相当于扑克牌发牌时,左拿第一张牌,右手摸牌,将右手的牌当作目标牌,与左手中的牌进行对比,使得左手中的牌从左至由,由小到大排序。即将最小的牌放在最左边
import random
import timeit
def randomList(n):
iList = []
for i in range(n):
iList.append(random.randrange(0,1000))
return iList
def bubblesort(iList):
if (len(iList)<=1):
return iList
for i in range(1,len(iList)):
for j in range(0,len(iList)-i):
if(iList[j]>iList[j+1]):
iList[j],iList[j+1] = iList[j+1],iList[j]
return iList
def selectsort(iList):
if(len(iList)<=1):
return iList
for i in range(0,len(iList)-1):
if iList[i] != min(iList[i:]):
minIndex = iList.index(min(iList[i:]))
iList[i],iList[minIndex] = iList[minIndex],iList[i]
return iList
def insetionsort(iList):
if(len(iList)<=1):
return iList
for right in range(1,len(iList)):
target = iList[right]
for left in range(0,right):
if target<=iList[left]:
iList[left+1:right+1] = iList[left:right]
iList[left] = target;
break
return iList
if __name__ == "__main__":
iList = randomList(20)
print(iList)
print(insetionsort(iList))
#print(timeit.timeit("selectsort(iList)","from _main_ import selectsort,iList",number=100))