1. 程式人生 > >python 歸併排序 與 快速排序 速度對比

python 歸併排序 與 快速排序 速度對比

import time


def merge(list,first,mid,last):
    left = list[first:mid+1]
    right = list[mid+1:last+1]
    while left != [] and right !=[]:
        if left[0] < right[0]:
            list[first] = left.pop(0)
        else:
            list[first] = right.pop(0)
        first +=1
    if left != []:
        list[first
:last+1] = left[:] elif right!= []: list[first:last+1] = right[:] def sort(first,last): # 歸併排序 global list mid = (last + first)//2 if first < last: sort(first,mid) sort(mid+1,last) merge(list,first,mid,last) def qsort(list): # 快速排序
l = list.pop() x = [] y = [] while list: m = list.pop() if m < l: x.append(m) else: y.append(m) if x: qsort(x) list.extend(x) list.append(l) if y: qsort(y) list.extend(y) return list list = [2
,4,6,8,1,3,6,7,9,11,17,13,12] T = time.time() sort(0,len(list)) # 歸併排序 print(list,time.time()-T) print('-'*30) list = [2,4,6,8,1,3,6,7,9,11,17,13,12] # 重置列表 T = time.time() list.sort() # 內建函式sort print(list,time.time()-T) print('-'*30) list = [2,4,6,8,1,3,6,7,9,11,17,13,12] T = time.time() qsort(list) # 快速排序 print(list,time.time()-T)

時間對比:

[1, 2, 3, 4, 6, 6, 7, 8, 9, 11, 12, 13, 17] 
5.3882598876953125e-05
------------------------------
[1, 2, 3, 4, 6, 6, 7, 8, 9, 11, 12, 13, 17]
 3.0994415283203125e-06
------------------------------
[1, 2, 3, 4, 6, 6, 7, 8, 9, 11, 12, 13, 17] 
4.076957702636719e-05

Process finished with exit code 0