【发布时间】:2017-07-30 14:07:22
【问题描述】:
我一直在测试各种其他排序算法(Selection、Quick、Bubble、Shell、Radix 等)以及插入排序的速度。然而,插入排序似乎是迄今为止最快的算法。我一直认为快速排序会是最快的。
这是我在 Python 3 中的插入排序和计时器函数的代码。
def InsertionSort(argShuffledList):
for index in range(1,len(argShuffledList)):
currentvalue = argShuffledList[index]
position = index
while position>0 and argShuffledList[position-1]>currentvalue:
argShuffledList[position]=argShuffledList[position-1]
position = position-1
argShuffledList[position]=currentvalue
return argShuffledList
def Timer(argFunction, *args): ## function for timing functions
dblStart = time.clock()
argFunction(*args)
intTime = "%.2f" % ((time.clock() - dblStart) * 1000000)
message = "Elasped Time: " + str(intTime) + " microseconds"
return message
insertionSortList = InsertionSort(insertionCopyList)
timeInsertionSortList = Timer(InsertionSort, insertionCopyList)
【问题讨论】:
-
列表有多长?此外,使用
time计时并不理想,请使用timeit模块。大家可以看看不同排序算法的复杂度here。 -
不要将 O(n^2) 算法与 O(n log n) 算法进行比较。它使比较毫无用处,除非您的目标是非常具体的 n 大小。
-
实际上,更详细一点,您只需为未指定大小的列表调用一次排序算法。即使您不想使用
timeit,您的测试用例也非常有限,您不可能使用这种方法对您的算法进行基准测试。 -
看起来您正在对列表进行排序,然后再次定时排序。但是第二次,列表已经排序,这是插入排序的绝对最佳情况。您确定对
InsertionSort(insertionCopyList)的第一次调用没有对insertionCopyList进行排序吗?
标签: python algorithm sorting quicksort insertion-sort