python
从一个有序数组查找指定元素
ll = [1,2,3…100]
普通查找:
如果查找的数字是66, 从最小开始查找,需要66次才能找到。
def search1(ll, num):
for i in ll:
if i==num:
return i
return None
二分查找说明:
如果查找的数字是99, 可以先从中间开始匹配:
第一次,50, 比66小
第二次,75, 比66大
第三次,63, 比66小
第四次,69, 比66大
第五次,66, 找到了
def search(ll, num):
#初始搜索范围
low = 0 #最小索引
hight = len(ll)-1 #最大索引
while low <=hight:
mid = math.ceil((low+hight)/2) #中间索引向上取整
if ll[mid]==num: #如果找到就返回
return mid
elif ll[mid] < num: #如果目标数比中间索引数大,则改变最小的搜索范围为中间索引向上
low = mid + 1
else:
hight = mid - 1 #如果目标数比中间索引数小,则改变最大的搜索范围为中间索引向下
return None
ll = [1,6,8,9,10,45]
print(search(ll, 9))
再如:查找联系人
import time
import math
import random
contact = []
for i in range(100):
name = ""
for j in range(5):
name += random.choice("abcdefghijklmnopqrstuvwxyz")
contact.append(name)
contact = sorted(contact)
def search(contact, name):
low = 0
hight = len(contact)-1
c = 0
while low<=hight:
c +=1
mid = math.ceil((low+hight)/2)
temp_list = [contact[mid],name]
temp_list = sorted(temp_list)
if contact[mid]==name:
return mid, c
if temp_list[0]==contact[mid]:
low = mid + 1
else:
hight = mid - 1
return None
#50个联系人
print(search(contact, contact[49])) #(49, 5)
#最多寻找次数
num = math.log2(50)
print(num) #5.643856189774724
#100个联系人
print(search(contact, contact[99])) #(99, 6)
#最多寻找次数
num = math.log2(100)
print(num) #6.643856189774724