为什么我的二分法搜索比python中的线性搜索慢?
在一次采访中,我被要求实施二分法搜索以缩短搜索时间,我提出了这个建议。我回家测试了一下,但看起来线性搜索比我的对分搜索做得更好。我做错什么了吗为什么我的二分法搜索比python中的线性搜索慢?,python,algorithm,search,Python,Algorithm,Search,在一次采访中,我被要求实施二分法搜索以缩短搜索时间,我提出了这个建议。我回家测试了一下,但看起来线性搜索比我的对分搜索做得更好。我做错什么了吗 import time sorted_list = range(0, 10000000) needle = 9999999 def split_list(sorted_list): half = len(sorted_list)/2 return sorted_list[:half], sorted_list[half:] def
import time
sorted_list = range(0, 10000000)
needle = 9999999
def split_list(sorted_list):
half = len(sorted_list)/2
return sorted_list[:half], sorted_list[half:]
def bisection(haystack, needle, length_of_list):
if len(haystack) <= length_of_list/5:
return haystack
first, last = split_list(haystack)
if needle < first[-1]:
return bisection(first, needle, length_of_list)
else:
return bisection(last, needle, length_of_list)
def linear_search(smaller_ist):
for ele in smaller_list:
if ele == needle:
return 0
start_time = time.time()
smaller_list = bisection(sorted_list, needle, len(sorted_list))
print linear_search(smaller_list)
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
print linear_search(sorted_list)
print("--- %s seconds ---" % (time.time() - start_time))
导入时间
排序列表=范围(0,10000000)
指针=9999999
def拆分列表(已排序列表):
half=len(已排序的列表)/2
返回已排序的_列表[:一半],已排序的_列表[一半:]
def二等分(草堆、针、长度列表):
如果len(haystack)是O(k),其中k是得到的切片的长度。您可以在split_list()
中的行return sorted_list[:half],sorted_list[half:][/code>中重复切片列表。对整个列表调用split_list()
的bisection
的顶级调用将花费O(n)来运行split_list
(因为左半部分的大小+右半部分的大小=n),其本身已经匹配线性搜索的时间复杂度
解决此问题的一种方法是,在对函数的递归调用中传递lowerBound
和upperBound
(其中顶级调用使用lowerBound
和upperBound
分别设置为0
和len(排序列表)
)。而列表的长度将是上界-下界
不用说,这里完全不需要切片。而是旋转索引。