我的python代码需要一些帮助。
我在下面做了两个功能,一个用于顺序(线性)搜索,另一个用于二进制搜索。
我想对给定列表中的每个大小值执行以下3件事:
1)生成给定列表大小的随机整数列表(1到1000,0000之间)
2)对列表上的-1进行顺序搜索,并记录顺序搜索所经过的时间
3)在排序后的列表上对-1进行二进制搜索(对列表进行排序之后),并记录二进制搜索所经过的时间
我所做的是:
def sequentialSearch(alist, item):
pos = 0
found = False
while pos < len(alist) and not found:
if alist[pos] == item:
found = True
else:
pos = pos + 1
return found
def binSearch(list, target):
list.sort()
return binSearchHelper(list, target, 0, len(list) - 1)
def binSearchHelper(list, target, left, right):
if left > right:
return False
middle = (left + right)//2
if list[middle] == target:
return True
elif list[middle] > target:
return binSearchHelper(list, target, left, middle - 1)
else:
return binSearchHelper(list, target, middle + 1, right)
import random
import time
list_sizes = [10,100,1000,10000,100000,1000000]
for size in list_sizes:
list = []
for x in range(size):
list.append(random.randint(1,10000000))
sequential_search_start_time = time.time()
sequentialSearch(list,-1)
sequential_search_end_time = time.time()
print("Time taken by linear search is = ",(sequential_search_end_time-sequential_search_start_time))
binary_search_start_time = time.time()
binSearch(list,-1)
binary_search_end_time = time.time()
print("Time taken by binary search is = ",(binary_search_end_time-binary_search_start_time))
print("\n")
我得到的输出是:
我们知道二进制搜索比线性搜索快得多。 那么,我只想知道为什么它显示二进制搜索所消耗的时间大于线性搜索所消耗的时间?
答案 0 :(得分:3)
1)您需要考虑排序时间。二进制搜索仅对排序后的列表起作用,因此排序需要花费时间,这会使它的时间复杂度达到O(nlogn)
。而且,根据您的情况,您是在计时器启动后对其进行排序的,因此它将更高。
2)您正在搜索列表中不存在的元素,即-1
,这不是二进制搜索的平均情况。二进制搜索最坏的情况是必须跳很多步才找不到元素。
3)请不要使用list
作为变量,它是python的关键字,您显然会覆盖它。使用其他东西。
现在,如果您对列表进行排序而不计时。结果发生了巨大变化。这是我的。
Time taken by linear search is = 9.059906005859375e-06
Time taken by binary search is = 8.58306884765625e-06
Time taken by linear search is = 1.2159347534179688e-05
Time taken by binary search is = 4.5299530029296875e-06
Time taken by linear search is = 0.00011110305786132812
Time taken by binary search is = 5.9604644775390625e-06
Time taken by linear search is = 0.0011129379272460938
Time taken by binary search is = 8.344650268554688e-06
Time taken by linear search is = 0.011270761489868164
Time taken by binary search is = 1.5497207641601562e-05
Time taken by linear search is = 0.11133551597595215
Time taken by binary search is = 1.7642974853515625e-05
我所做的只是在计时之前对列表进行排序。方式,比您必须对其进行排序和全部搜索的方式更好。