结论:快速排序效率最高,合并排序其次,直接插入效率肯定是最低的。
import time
from functools import wraps
from timeit import default_timer as timer
import random
import matplotlib.pyplot as plt
def timefn(fn):
"""计算性能的修饰器"""
@wraps(fn)
def measure_time(*args, **kwargs):
t1 = time.time()
result = fn(*args, **kwargs)
t2 = time.time()
return result
return measure_time
@timefn
def disort(a): # 直接插入排序
l=len(a)
for i in range(l):
temp = a[i]
j = i-1
while j >= 0 and a[j] > temp:
a[j+1] = a[j]
j = j-1
a[j+1] = temp
return a
def mergesort(a): # 合并排序功能函数
l = len(a)
b = []
c = []
b = a[0:l//2+l%2:1]
c = a[l//2+l%2::1]
b.sort()
print(b)
c.sort()
print(c)
a=[]
i=0
j=0
while i<l//2 and j<l//2: # 循环条件
if b[i]>c[j]:
a.append(c[j])
j+=1
else:
a.append(b[i])
i+=1
if i==l//2+l%2: # 循环关键部分
a=a+c[j::1]
if j==l//2+l%2: # 若没有此处的if程序健壮性不强
a=a+b[i::1]
return a
def partition(arr, low, high):
i = (low - 1) # 最小元素索引
pivot = arr[high]
for j in range(low, high):
# 当前元素小于或等于 pivot
if arr[j] <= pivot:
i = i + 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return (i + 1)
# 快速排序函数
def Quick_sort(list):
"""快速排序"""
if len(list) < 2:
return list
# 选取基准,随便选哪个都可以,选中间的便于理解
mid = list[len(list) // 2]
# 定义基准值左右两个数列
left, right = [], []
# 从原始数组中移除基准值
list.remove(mid)
for item in list:
# 大于基准值放右边
if item >= mid:
right.append(item)
else:
# 小于基准值放左边
left.append(item)
# 使用迭代进行比较
return Quick_sort(left) + [mid] + Quick_sort(right)
listtime1=[]
listtime2=[]
listtime3=[]
for m in range(1,2002,200): # 随机生成测试list
b=[random.randint(0,1000)for i in range(m)]
b1=b
b2=b
tic = timer()
mergesort(b1)
tic1= timer()
disort(b2)
tic2=timer()
Quick_sort(b)
tic3=timer()
listtime1.append(tic1 - tic)
listtime2.append(tic2 - tic1)
listtime3.append(tic3 - tic2)
y1=listtime1
y2=listtime2
y3=listtime3
print(y1)
print(y2)
print(y3)
def plot_double_lines(n, x, y1, y2, pic_name): # 绘制图标
# initialize plot parameters
print('picture name: %s, len of data: %d' % (pic_name, n))
plt.rcParams['figure.figsize'] = (10 * 16 / 9, 10)
plt.subplots_adjust(left=0.06, right=0.94, top=0.92, bottom=0.08)
# plot curve 1
plt.plot(x, y1, label='mergesort')
# plot curve 2
plt.plot(x, y2, label='disort')
# plot curve 3
plt.plot(x, y3, label='quicksort')
# show the legend
plt.legend()
# show the picture
plt.show()
if __name__ == '__main__':
xs = range(1,2002,200)
y1s = listtime1
y2s = listtime2
y3s = listtime2
plot_double_lines(len(xs), xs, y1s, y2s, y3s)