直接插入排序伪代码:
ALGORITHM InsertionSort( A[0..n-1] ) // 对给定序列进行直接插入排序
// 输入:大小为n的无序序列A
// 输出:按非递减排列的序列
A for i ← 1 to n-1 do
temp ← A[i]
j ← i-1
while j ≥ 0 and A[j] > temp do
A[j+1] ← A[j]
j ← j –1
A[j+1] ←temp
合并排序的递归算法伪代码:
算法 MergeSort(A[0..n-1] )
// 输入:未排序序列A[0..n-1]
// 输出:已排序序列A[0..n-1]
if n > 1
copy A[0..n/2-1] to B[0..n/2-1]
copy A[n/2..n-1] to C[0..n/2-1]
MergeSort( B )
MergeSort( C )
Merge( B,C,A )
其中,Merge(B,C,A)是将有序数组B、C合并为有序数组A的算法。
算法 Merge(B[0..p-1],C[0..q-1],A[0..p+q-1])
i=0,j=0,k=0;
while i<p and j<q do\
if B[i]≤C[j]
A[k]=B[i], i=i+1
else
A[k]=C[j], j=j+1
k=k+1
if i=p
copy C[i..q-1] to A[k..p+q-1]
else
copy B[0..p-1] to A[0..p+q-1]
完整对比代码
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
listtime1=[]
listtime2=[]
for m in range(1,22102,2000): # 随机生成测试list
b=[random.randint(0,1000)for i in range(m)]
tic = timer()
mergesort(b)
tic1= timer()
disort(b)
tic2=timer()
listtime1.append(tic1 - tic)
listtime2.append(tic2 - tic1)
y1=listtime1
y2=listtime2
print(y1)
print(y2)
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')
# show the legend
plt.legend()
# show the picture
plt.show()
if __name__ == '__main__':
xs = range(1,22102,2000)
y1s = listtime1
y2s = listtime2
plot_double_lines(len(xs), xs, y1s, y2s, 'Two Curves')
对比关系图:纵坐标单位’s’