什么是搜索
搜索是在项集合中查找特定项的算法过程。搜索通常对于项是否存在返回 True 或 False。有时它可能返回项被找到的地方。在python中使用in即可完成对元素的查找,但是
顺序查找
算法原理: 在项集合中按照顺序对元素进行比较,即顺序查找,其时间为O(n)
优缺点: 如果查询的元素位置在中间,则时间只有n/2,但如果没有相应匹配的时候,时间为n。如果集合是有序的列表,则可以在顺序查找过程中增加一个判断条件,以减少消耗的时间,判断的条件是查找元素和列表内的元素比较,如果出现比元素大的情况,就说明查找的元素不在集合中。所以对序列先做排序会提升顺序查找的速率。
代码实现:
# 顺序搜索1
def sequentialsearch(alist,item):
pos=0
found = False
while pos <len(alist) and not found:
if item != alist[pos]:
pos +=1
else:
found = True
return found
alist=[1,2,3,4,5]
print(sequentialsearch(alist,5))
print(sequentialsearch(alist,1))
# 顺序搜索+条件
def sequentialsearch2(alist,item):
pos=0
found = False
while pos <len(alist) and not found:
if item != alist[pos]:
pos +=1
elif alist[pos]>item:
break
else:
found = True
return found
alist=[1,2,6,9,11]
print(sequentialsearch(alist,5))
print(sequentialsearch(alist,9))
二分查找
算法原理: 已知对于查找算法,有序列表会增加效率。在有序列表下,为了提高查找速率,我们从一个列表中间开始进行比较,这样时间为O(logn)。
优缺点: 即使二分查找通常比顺序查找更好,但重要的是要注意,对于小的 n 值,排序的额外成本可能不值得。事实上,我们应该经常考虑采取额外的分类工作是否使搜索获得好处。如果我们可以排序一次,然后查找多次,排序的成本就不那么重要。然而,对于大型列表,一次排序可能是非常昂贵,从一开始就执行顺序查找可能是最好的选择。
代码实现:
def binarysearch(alist, item):
mid = len(alist) // 2
left = alist[:mid]
right = alist[mid:]
found = False
while len(alist) > 1 and not found:
if item == alist[mid]:
return True
elif item < alist[mid]:
return binarysearch(left, item)
else:
return binarysearch(right, item)
if alist[0] != item:
return found
Hash查找
算法原理: Hash查找的原理基于hash函数,列表通过hash函数将列表元素映射到一个散列表中,其中散列表的索引即hash函数映射的值,对应位置储存的即列表的元素。通过散列表进行查找,其时间复杂度为O(1)。
Hash函数 1. 余数法:将项除以散列表的长队,返回剩余部分作为散列值(h(item) = item%(len(l))
优缺点: 需要处理散列表的冲突