gpt4 book ai didi

python - bisect算法的复杂度是多少?

转载 作者:太空狗 更新时间:2023-10-30 00:26:51 26 4
gpt4 key购买 nike

我编写代码是为了了解在搜索列表中的元素时哪一个更快。结果是平分的。我不明白的是什么是二分法算法的复杂度,它是否使用 Van Emde Boas 树?

#python inbuilt list search using 'in' took 0.0702499200317 secs

def mul3():
a = [1, 2, 4, 5, 6, 7, 8, 10, 12, 42, 55, 65, 69, 95, 96, 101, 156, 199]
for x in a:
if x in a:
print x, "True"
else:
print x, "False"

#using bisect took 0.0649611193601

def mul4():
a = [1, 2, 4, 5, 6, 7, 8, 10, 12, 42, 55, 65, 69, 95, 96, 101, 156, 199]
import bisect
for x in a:
locate = bisect.bisect_left(a, x)
if locate == len(a) or a[locate] != x:
print False
print True

#using binary search took 0.0651483638284


a = [1, 2, 4, 5, 6, 7, 8, 10, 12, 42, 55, 65, 69, 95, 96, 101, 156, 199]


for x in a:
lo = 0
hi = 18
while lo < hi:
mid = (lo+hi)//2
midval = a[mid]
if midval < x:
lo = mid+1
elif midval > x:
hi = mid
else:
print True
lo = hi

引用: http://docs.python.org/library/bisect.html

最佳答案

它使用二进制搜索,使其成为 O(log n)。

关于python - bisect算法的复杂度是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12022249/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com