时间:2021-07-01 10:21:17 帮助过:80人阅读
用Python实现二分查找示例:
>>> def find(self, num): l = len(self) first = 0 end = l - 1 mid = 0 if l == 0: self.insert(0,num) return False while first < end: mid = (first + end)/2 if num > self[mid]: first = mid + 1 elif num < self[mid]: end = mid - 1 else: break if first == end: if self[first] > num: self.insert(first, num) return False elif self[first] < num: self.insert(first + 1, num) return False else: return True elif first > end: self.insert(first, num) return False else: return True >>> list_d = ['a','b','c','d','e','f','d','t'] >>> value_d = 't' >>> aa=find(list_d,value_d) >>> aa True >>> value_d='ha' >>> aa=find(list_d,value_d) >>> aa False