1 #顺序查找即在给定范围内逐个遍历,查找需要的数据直到找到或者退出,适合任何类型的查找对象。复杂度为O(n)下面一列表为例,展示顺序查找算法 2 list1 = [i for i in range(100)] #使用列表生成式,生成一个0~99的步长为1列表。 3 find_num = int(input("inpute you want find num")) 4 for i in range(len(list1)): 5 if find_num == list1[i]: 6 print("num index is %d"%i) 7 break 8 print("the num not in list") 9 10 #二分查找。二分查找适合查找对象已完成排序,复杂度为O(log n)还是以list1作为查找对象,假设列表按照升序排列 11 def Find_Num(num, list1): 12 low = 0 13 top = len(list1) - 1 14 if len(list1) == 0: 15 print("list is null") 16 exit() 17 while low <= top: 18 task = int((low + top)/2) 19 guess = list1[task] 20 if num == list1[task]: 21 print("the num1 index is %d"%task) 22 break 23 if num > list1[task]: 24 low = task + 1 25 elif num < list1[task]: 26 top = task - 1 27 else: 28 print("num not in list1") 29 Find_Num(20, list1)
来源:https://www.cnblogs.com/flags-blog/p/11932182.html