本文实例讲述了Python排序搜索基本算法之归并排序。分享给大家供大家参考,具体如下:
归并排序最令人兴奋的特点是:不论输入是什么样的,它对N个元素的序列排序所用时间与NlogN成正比。代码如下:
# coding:utf-8
defmergesort(seq):
iflen(seq)<=1:
returnseq
mid=int(len(seq)/2)
left=mergesort(seq[:mid])
right=mergesort(seq[mid:])
returnmerge(left,right)
defmerge(left,right):
result=[]
i,j=0,0
whilei
ifleft[i]<=right[j]:
result.append(left[i])
i
=1
else:
result.append(right[j])
j
=1
result =left[i:]
result =right[j:]
returnresult
if__name__=='__main__':
print("脚本之家测试结果:")
seq=[4,5,7,9,7,5,1,0,7,-2,3,-99,6]
print(mergesort(seq))
运行结果: