(python)插入排序递归算法与非递归算法比较实验
实验题目
插入排序递归算法与非递归算法比较实验
实验要求
画出运行时间与n变化曲线对比图,并分析原因
实验目的
1、 掌握递归算法的思想
2、 编写实现插入排序的递归与非递归算法
3、 比较插入排序的递归与非递归实现不同n值所耗费的时间
实验步骤
1、递归实现插入排序算法
#递归实现插入排序
def rec_Insert_sort(seq, i):
if i == 0:
return
rec_Insert_sort(seq, i-1)
j = i
while j>0 and seq[j-1]>seq[j]:
seq[j-1], seq[j] = seq[j], seq[j-1]
j -= 1
2、非递归实现插入排序算法
#非递归实现插入排序
def Insert_sort(seq,i):
for i in range(1, i):
j = i
while j>0 and seq[j-1]>seq[j]:
seq[j-1], seq[j] = seq[j], seq[j-1]
j -= 1
3、统计函数运行时间
#函数运算时间
def time_Counter(func, seq, i):
time_start = time.time()
func(seq,i)
time_end = time.time()
return time_end-time_start
4、可视化显示实验结果
def ShowTimes(N,time1, time2):
#设置汉字格式
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
plt.figure("Lab2")
plt.title(u'不同n值递归与非递归插入排序算法所耗费的时间',FontProperties=font)
plt.xlabel(u'n值',FontProperties=font)
plt.