时间复杂度:
最好情况:; 平均情况:
最坏:
稳定
import random
import time
def insertSort(arr):
for p in range(1,len(arr)):
temp=arr[p]
j=p
# j的前一个跟p位置的值比较
while j-1>=0 and temp <arr[j-1] :
# j-1的数据往后挪一位
arr[j]=arr[j-1]
j-=1
arr[j]=temp
return arr
def test1():
arr=[random.randint(0,99) for _ in range(0,15)]
print(arr)
insertSort(arr)
print(arr)
def test2():
arr=[random.randint(0,50000) for _ in range(0,50000)]
start=time.time()
print("start:",start)
insertSort(arr)
end =time.time()
print("end:",end)
print("cost time:",end-start)
if __name__=="__main__":
test1()
# cost time: 84.39235424995422
# test2()
结果
test1:
[86, 53, 92, 28, 69, 95, 8, 11, 85, 21, 20, 95, 81, 56, 19]
[8, 11, 19, 20, 21, 28, 53, 56, 69, 81, 85, 86, 92, 95, 95]
test2:
start: 1710335777.9907892
end: 1710335863.6678803
cost time: 85.67709112167358