[英]Insertion sort algorithm runtime
當我發現一個版本的插入排序的運行時間比另一個版本的插入排序的運行時間更快時,我試圖查看不同排序算法的運行時間差異。 算法的版本看起來幾乎相同(差異只有 1 分)。 我不知道為什么。 一個版本(較慢的一個)來自 w3resource,另一個(較快的一個)來自 geeksforgeeks。 我正在python中進行比較。
極客的極客
def insertion_sort_geeks(a):
"""
https://www.geeksforgeeks.org/insertion-sort/
:param a: Array
:return: time to sort
"""
start = time.time()
for i in range(1, len(a)):
current_val = a[i]
j = i - 1
while j >= 0 and a[j] > current_val:
a[j + 1] = a[j]
j -= 1
a[j + 1] = current_val
end = time.time()
return end - start
W3Resource算法
def insertion_sort_w3(a):
"""
https://www.w3resource.com/python-exercises/data-structures-and-algorithms/python-search-and-sorting-exercise-6.php
:param a: array
:return: time to sort
"""
start = time.time()
for i in range(1, len(a)):
current_val = a[i]
j = i
while j > 0 and a[j - 1] > current_val:
a[j] = a[j - 1]
j -= 1
a[j] = current_val
end = time.time()
return end - start
當我運行這些算法時,我一直發現 geeksforgeeks 算法更快,但不知道為什么?
-- 對包含 10,000 個整數的列表進行排序(隨機)
Insertion Sort Geek Insertion Sort W3
4.727362155914307 5.441751718521118
4.595118761062622 5.537100791931152
4.742804050445557 5.453729867935181
4.684415102005005 5.44006609916687
4.790072202682495 5.50256085395813
4.789106845855713 5.894493818283081
5.104598045349121 6.107465982437134
5.100121021270752 5.738892078399658
4.825102090835571 5.55505895614624
4.877285003662109 5.7944769859313965
https://github.com/ShamsAnsari/Algorithms
https://www.w3resource.com/python-exercises/data-structures-and-algorithms/python-search-and-sorting-exercise-6.php https://www.geeksforgeeks.org/insertion-sort/
頂部的每個外循環定義 j 一次。 10.000 次。 在底部,您必須減少每個內循環控制中的 j 以進行測試。 那是 (10.000 * 10.000 - 10.000)/2 作為上限(感謝@trincot 糾正了這個)操作更多。
較慢的版本:
j = i
while j > 0 and a[j - 1] > current_val:
更快的版本:
j = i - 1
while j >= 0 and a[j] > current_val:
我認為 a[j - 1] 是主要區別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.