# 冒泡排序
def bubble(ls):
length = len(ls)
while length>1:
for i in range(length-1):
if ls[i]>ls[i+1]:
ls[i],ls[i+1] = ls[i+1],ls[i]
length -= 1
return ls
# 插入排序
def myinsert(ls):
for i in range(1,len(ls)):
temp = ls[i]
j = i
while j>0 and ls[j-1]>temp:
ls[j] = ls[j-1]
j-=1
ls[j] = temp
return ls
# 快速排序
def quick(ls):
if len(ls)<2:
return ls
else:
left,right = [],[]
for i in ls[:-1]:
if i >= ls[-1]:
right.append(i)
else:
left.append(i)
return quick(left)+[ls[-1]]+quick(right)
from numpy import random
from time import time
import matplotlib.pyplot as plt
time_bubble,time_insert,time_quick = [],[],[]
x = [100,500,1000,3000,5000]
for i in x:
ls1 = list(random.randint(10000,size=i))
ls2,ls3 = ls1.copy(),ls1.copy()
begin = time()
lsb = bubble(ls1)
time_bubble.append(time()-begin)
begin = time()
lsi = myinsert(ls2)
time_insert.append(time()-begin)
begin = time()
lsq = quick(ls3)
time_quick.append(time()-begin)
plt.plot(x,time_bubble,label='bubble')
plt.plot(x,time_insert,label='insert')
plt.plot(x,time_quick,label='quick')
plt.xlabel("data size")
plt.ylabel("seconds")
plt.xticks((100,500,1000,3000,5000))
plt.title("Three algorithms")
plt.legend()
#plt.savefig("picture1",dpi=600)
plt.show()