线性查找
'''
列表线性查找
线性查找就是从列表起始位置一次查询,直到查询到目标值,或者遍历整个列表完毕才结算查找过程
线性查找复杂度 O(n),比较慢
'''
from call_time import *
@call_time
def liner_search(list, value):
for index, element in enumerate(list):
if element == value:
return index
#如果找不到就返回 None
return None
二分查找
'''
二分查找:从中间位置进行查找,大了就往左边移动一般,小了往左边移动一般,每次查找缩小一半的候选区
前提:必须是有序列表才可以使用二分查找,二分复杂度 Log(n) 比较快
'''
@call_time
def binary_search(list, value):
low = 0
high = len(list) - 1
while low <= high:
'''候选区有值,需要继续查找'''
mid = (low + high) // 2 # 整除
if list[mid] == value:
return mid
elif list[mid] > value:
high = mid - 1 # right 左移
else:
low = mid + 1 # left 右移动
#如果找不到就返回 None
return None
补充和说明
'''
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中
seq = ['one', 'two', 'three']
for key,element in enumerate(seq):
print(key,element)
输出
0 one
1 two
2 three
'''
'''
nums.index(n) 走的线性查找
'''