如何解决二分搜索 vs. 线性搜索 奇怪的时间
我有一个大约 10 万个整数的列表,我正在测试线性搜索与二分搜索的概念。看起来我的线性搜索实际上比我的二分搜索快。我不确定我明白为什么会这样。有什么见解吗?
def linear_search(big_list,element):
"""
Iterate over an array and return the index of the first occurance of the item.
Use to determine the time it take a standard seach to complate.
Compare to binary search to see the difference in speed.
% time ./searchalgo.py
Results: time ./main.py 0.35s user 0.09s system 31% cpu 1.395 total
"""
for i in range(len(big_list)):
if big_list[i] == element:
# Returning the element in the list.
return i
return -1
print(linear_search(big_list,999990))
def linear_binary_search(big_list,value):
"""
Divide and concuer approach
- Sort the array.
- Is the value I am searching for equal to the middle element of the array.
- Compare is the middle element smaller orlarger than the element you are looking for?
- If smaller then perform linear search to the right.
- If larger then perform linear seach to the left.
% time ./searchalgo.py
Results: 0.57s user 0.18s system 32% cpu 2.344 total
"""
big_list = sorted(big_list)
left,right = 0,len(big_list) - 1
index = (left + right) // 2
while big_list[index] != value:
if big_list[index] == value:
return index
if big_list[index] < value:
index = index + 1
elif big_list[index] > value:
index = index - 1
print(big_list[index])
# linear_binary_search(big_list,999990)
Output of the linear search time:
./main.py 0.26s user 0.08s system 94% cpu 0.355 total
Output of the binary search time:
./main.py 0.39s user 0.11s system 45% cpu 1.103 total
解决方法
由于单次遍历,您的第一个算法时间复杂度为 O(n)。但是在您第二次遍历的情况下,首先对需要 O(nlogn) 时间的元素进行排序,然后进行搜索需要 O(logn)。所以你的第二个算法的时间复杂度将是 O(nlogn) + O(logn),这比你的第一个算法的时间复杂度要大。
,def binary_search(sorted_list,target):
if not sorted_list:
return None
mid = len(sorted_list)//2
if sorted_list[mid] == target:
return target
if sorted_list[mid] < target:
return binary_search(sorted_list[mid+1:],target)
return binary_search(sorted_list[:mid],target)
我很确定实际上会正确地递归实现二进制搜索(这对我的大脑来说更容易处理)……还有内置的 bisect
库,它基本上为您实现了 binary_search
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。