我通过两种方式编写了一个简单的插入排序函数。
def binary_search(the_array, item, start, end):
if start == end:
if the_array[start] > item:
return start
else:
return start + 1
if start > end:
return start
mid = round((start + end)/ 2)
if the_array[mid] < item:
return binary_search(the_array, item, mid + 1, end)
elif the_array[mid] > item:
return binary_search(the_array, item, start, mid - 1)
else:
return mid
def insertion_sort(the_array):
l = len(the_array)
start = time.process_time()
for index in range(1, l):
value = the_array[index]
pos = binary_search(the_array, value, 0, index - 1)
#Way A:
#for p in range(index,pos,-1):
# the_array[p] = the_array[p-1]
#the_array[pos] = value
#Way B:
#the_array = the_array[:pos] + [value] + the_array[pos:index] + the_array[index+1:]
end = time.process_time()
print("Cost time:",end-start)
return the_array
A:
for p in range(index,pos,-1):
the_array[p] = the_array[p-1]
the_array[pos] = value
乙:
the_array = the_array[:pos] + [value] + the_array[pos:index] + the_array[index+1:]
我不擅长python 。在我的性能测试中,B方式比A方式快。我使用python time.process_time来获取时间偏移。
那么问题为什么B方式比A方式快? 请帮助我。谢谢
更新:我使用 10000 个随机整数来测试 A 和 B。
for x in range(0,10000):
data.append(random.randint(0,10000))
A路花费2.3125s B路花费0.890625s。
一天后,没有答案告诉我为什么,所以我决定阅读一本关于此的书。在“高性能 Python”中,我找到了原因的答案!如果你想知道你可以看到我自己的答案。
HUH函数
富国沪深
相关分类