import numpy as np;
import matplotlib.pyplot as plt;
from time import time;
def bbsort(lll):
length = len(lll);
if length == 1:
return lll;
for i in range(length-1):
if lll[i] > lll[i+1]:
lll[i],lll[i+1] = lll[i+1],lll[i];
new = bbsort(lll[:-1])+[lll[-1]];
return new;
def bbsort2(lll):
for i in range(len(lll)-1):
for j in range(len(lll)-i-1):
if lll[j] > lll[j+1]:
lll[j],lll[j+1] = lll[j+1],lll[j];
return lll;
if __name__ == '__main__':
tt1 = [];
tt2 = [];
x = [i for i in range(1,900,3)];
for j in range(1,900,3):
height = np.round(np.random.rand(j)*100+100,2).tolist();
t1 = time();
height_new = bbsort(height);
t2 = time();
height = np.round(np.random.rand(j)*100+100,2).tolist();
t3 = time();
height_new2 = bbsort2(height);
t4 = time();
tt1.append(t2-t1);
tt2.append(t4-t3);
plt.plot(x,tt1,'r--',label='recursion');
plt.plot(x,tt2,'b--',label='for');
plt.xlabel('length of list/k');
plt.ylabel('time/s');
plt.legend(loc = 'upper left');
plt.show();
加个flag,用来for循环中查看是否有数据交换,如果没有则排序完毕,减少时间
def bbsort2(L):
for i in range(len(L)-1):
flag = False;
for j in range(len(L)-i-1):
if L[j] > L[j+1]:
L[j],L[j+1] = L[j+1],L[j];
flag = True;
if flag == False: #如果这一轮循环未发生数据交换,则可以停止排序
break;
return L;