二分法查找:在一组有序的数据中进行查找,首先与中间的数先比较,如果查找的数大于中间的数,则要查找的数在前半段,否则在后半段,这样就会排除一半的数据,如此递归进行下去,则会极大的提高查找的速度。下面利用python代码实现二分查找
def binary_search(array,key): low = 0 high = len(array) - 1 while low < high: mid = int((low + high)/2) if key < array[mid]: high = mid - 1 elif key > array[mid]: low = mid + 1 else: return mid return False def main(): array = [1,2,3,4,5,6,7,8,9,10,14,15,17,21,24,28,35,35,37,39] result = binary_search(array,7) print(result) if __name__ == ‘__main__‘: main()
排序后会返回所查数据在列表中的索引,如果没查找到返回False