[Python] 纯文本查看 复制代码
def linear_search(data, search_for):
"""线性搜索"""
search_at = 0
search_res = False
while search_at < len(data) and search_res is False:
if data[search_at] == search_for:
search_res = True
else:
search_at += 1
return search_res
lis = [5, 10, 7, 35, 12, 26, 41]
print(linear_search(lis, 12))
print(linear_search(lis, 6))
[Python] 纯文本查看 复制代码
def insert_search(data,x):
"""插值搜索"""
idx0 = 0
idxn = (len(data) - 1)
while idx0 <= idxn and x >= data[idx0] and x <= data[idxn]:
mid = idx0 +int(((float(idxn - idx0)/(data[idxn] - data[idx0])) * (x - data[idx0])))
if data[mid] == x:
return "在下标为"+str(mid) + "的位置找到了" + str(x)
if data[mid] < x:
idx0 = mid + 1
return "没有搜索到" + str(x)
lis = [2, 6, 11, 19, 27, 31, 45, 121]
print(insert_search(lis, 31))
print(insert_search(lis, 3))