python算法——快速排序算法

 

 

归并排序

 1 def merge(li, low,mid, high):
 2     i = low
 3     j = mid+1
 4     ltmp = []
 5     while i<=mid and j <=high:
 6         if li[i]<li[j]:
 7             ltmp.append(li[i])
 8             i += 1
 9         else:
10             ltmp.append(li[j])
11             j += 1
12     while i<=mid:
13         ltmp.append(li[i])
14         i += 1
15     while j<=high:
16         ltmp.append(li[j])
17         j += 1
18     li[low:high+1]=ltmp
19 # li = [1,5,7,8,9,2,5,7,10]
20 # merge(li,0,len(li)//2,len(li)-1)
21 # 本算法时间复杂度为O(n*logn)
22 def merge_sort(li,low,high):
23     if low<high:
24         mid = (low+high)//2
25         merge_sort(li,low,mid)
26         merge_sort(li,mid+1,high)
27         merge(li,low,mid,high)
28 
29 
30 import time
31 def timer(func):
32     def inner(*args,**kwargs):
33         start = time.time()
34         ret = func(*args,**kwargs)
35         end = time.time()
36         print(end-start)
37         return ret
38     return inner
39 @timer
40 def outer(li,low,high):
41     merge_sort(li,low,high)
42 # import random
43 # li = list(range(1000))
44 # random.shuffle(li)
45 # print(li)
46 # outer(li,0,len(li)-1)   # 1000个数据费时0.004s
47 # print(li)
48 
49 # li = list(range(10000))
50 # random.shuffle(li)
51 # print(li)
52 # outer(li,0,len(li)-1)   # 10000个数据费时0.05s
53 # print(li)

 

posted @ 2018-01-29 11:18  liuyankui163  阅读(132)  评论(0编辑  收藏  举报