时序排序功能

时间:2016-04-11 03:27:05

标签: python

import time

def timeSort(sortfn, L):
   t1 = time.time()
   sortfn(L)
   t2 = time.time()
   return (t2 - t1)

# try, e.g.,
# l = mixup(list(range(4000)))
# timeAllSorts(l)
def timeAllSorts(L):

    Lcopy = L[:]
    sTime = timeSort(selectionSort, Lcopy)
    Lcopy = L[:]
    iTime = timeSort(insertionSort, Lcopy)
    Lcopy = L[:]
    mTime = timeSort(mergeSort, Lcopy)
    Lcopy = L[:]
    biTime = timeSort(builtinSort, Lcopy)
    Lcopy = L[:]
    qTime = timeSort(quicksort, Lcopy)

   print("{}\t sel: {:.2f}\t ins: {:.2f}\t merge: {:.2f}\t builtin: {:.2f}\t quick:{:.2f}".format(len(L), sTime, iTime, mTime, biTime,qTime))

我有多个排序功能,我无法将它们全部放在代码中,例如我的quicksort():

import random
def quicksort(L):
    if len(L)<2: return L
    pivot_element = random.choice(L)
    small = [i for i in L if i< pivot_element]
    medium = [i for i in L if i==pivot_element]
    large = [i for i in L if i> pivot_element]
    return quicksort(small) + medium + quicksort(large)

当我运行timeAllSorts函数时,它为每个函数返回0.00的运行时间,我不确定为什么会发生这种情况。也许用我的印刷声明?

>>> timeAllSorts([12,5,13,8,9,65])
6    sel: 0.00   ins: 0.00   merge: 0.00     builtin: 0.00   quick:0.00

1 个答案:

答案 0 :(得分:2)

排序5个整数即使是最差的排序算法也会花费时间。要正确测试,你需要几百甚至几千件物品。

例如,testing with 8000 items shows that the sorted inbuilt is still "0 seconds", while quicksort is "0.05" seconds

import time

def timeSort(sortfn, L):
   t1 = time.time()
   sortfn(L)
   t2 = time.time()
   print t2-t1
   return (t2 - t1)

# try, e.g.,
# l = mixup(list(range(4000)))
# timeAllSorts(l)

import random
def quicksort(L):
    if len(L)<2: return L
    pivot_element = random.choice(L)
    small = [i for i in L if i< pivot_element]
    medium = [i for i in L if i==pivot_element]
    large = [i for i in L if i> pivot_element]
    return quicksort(small) + medium + quicksort(large)

def timeAllSorts(L):

    Lcopy = L[:]
    qTime = timeSort(quicksort, Lcopy)
    sTime = timeSort(sorted, Lcopy)

    print("{}\t sel:{:.2f} quick:{:.2f}".format(len(L),sTime, qTime))

l = list(range(8000,1,-1))
timeAllSorts(l)
7999   sel:0.00 quick:0.05