比较冒泡、插入、快速的运行效率

# 冒泡排序
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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值