本文实例讲述了Python排序搜索基本算法之归并排序。分享给大家供大家参考,具体如下:
归并排序最令人兴奋的特点是:不论输入是什么样的,它对N个元素的序列排序所用时间与NlogN成正比。代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
# coding:utf-8
def mergesort(seq):
if len (seq)< = 1 :
return seq
mid = int ( len (seq) / 2 )
left = mergesort(seq[:mid])
right = mergesort(seq[mid:])
return merge(left,right)
def merge(left,right):
result = []
i,j = 0 , 0
while i< len (left) and j< len (right):
if left[i]< = right[j]:
result.append(left[i])
i + = 1
else :
result.append(right[j])
j + = 1
result + = left[i:]
result + = right[j:]
return result
if __name__ = = '__main__' :
print ( "服务器之家测试结果:" )
seq = [ 4 , 5 , 7 , 9 , 7 , 5 , 1 , 0 , 7 , - 2 , 3 , - 99 , 6 ]
print (mergesort(seq))
|
运行结果:
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://blog.csdn.net/littlethunder/article/details/9472301