有序查找:
def linear_search(data_set,value): for i in range(len(data_set)): if data_set[i] == value: return i return
二分查找:
def bin_search(data_set,value): low=0 high = len(data_set)-1 while low <= high: mid = (low+high)//2 if data_set[mid] == value: return mid elif data_set[mid] > value: high = mid-1 else: low = mid+1 a = bin_search(range(1,40),24) print(a)
注意:要求列表一定是有序的
例子:给定一个学生名单,包括姓名,年龄,id,按id从小到大有序排列,要求给出任意id值,查找对应的学生信息
import random def random_list(n): result = [] ids= list(range(1001,1001+n)) a1 = ['赵','钱','孙','李'] a2 = ['力','好'] a3 = ['强','国'] for i in range(n): age = random.randint(18,60) id = ids[i] name = random.choice(a1)+random.choice(a2)+random.choice(a3) dict = { 'id':id, 'name':name, 'age':age, } result.append(dict) return result def bin_search(data_set,value): low=0 high = len(data_set)-1 while low <= high: mid = (low+high)//2 if data_set[mid]['id'] == value: return data_set[mid] elif data_set[mid]['id'] > value: high = mid-1 else: low = mid+1 data_set = random_list(10000) print(bin_search(data_set,7654))
两种算法的时间复杂度分别为O(n)和O(logn)