二分查找是一个基础的算法,也是面试中常考的一个知识点。二分查找就是将查找的键和子数组的中间键作比较,如果被查找的键小于中间键,就在左子数组继续查找;如果大于中间键,就在右子数组中查找,否则中间键就是要找的元素。
使用循环和递归两种方法:
import time def mytime(func): def inner(*args, **kwargs): t1 = time.time() func(*args, **kwargs) t2 = time.time() print('time costed is {}.'.format(t2-t1)) return inner @mytime def bin_ser(data, li): if len(li) > 0: left = 0 right = len(li) - 1 else: print('list is too short!') return while left < right: mid = (left + right) // 2 if li[mid] > data: right = mid elif li[mid] < data: left = mid else: print('1-the position is {}.'.format(mid)) break @mytime def bin_ser2(data, li): def bin_mid(left, mid, right): if li[mid] > data: right = mid elif li[mid] < data: left = mid else: print('2-the position is {}.'.format(mid)) left = right mid = (left + right) // 2 if left < right: return bin_mid(left, mid, right) left = 0 right = len(li) - 1 mid = (left + right) // 2 bin_mid(left, mid, right) l = list(range(40, 10000)) bin_ser(42, l) bin_ser2(42, l)