Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我的二分法搜索比python中的线性搜索慢?_Python_Algorithm_Search - Fatal编程技术网

为什么我的二分法搜索比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(排序列表)
)。而列表的
长度将是
上界-下界

不用说,这里完全不需要切片。而是旋转索引。