python3--算法基础:二分查找/折半查找
算法基础:二分查找/折半查找
#!/usr/bin/env python # -*- coding:utf-8 -*- # 算法基础:二分查找/折半查找 def binarySearch(dataSource, find_n): mid = int(len(dataSource) / 2) if len(dataSource) >= 1: if dataSource[mid] > find_n: print("data in left of [%s]" % (dataSource[mid])) binarySearch(dataSource[:mid], find_n) elif dataSource[mid] < find_n: print("data in right of [%s]" % (dataSource[mid])) binarySearch(dataSource[mid:], find_n) else: print("find data is : [%s]" % (dataSource[mid])) else: print("not find data ...")
以上代码运行结果:
3333 data in left of [4999] data in right of [2500] data in right of [3748] data in right of [4372] data in right of [4684] data in right of [4840] data in right of [4918] data in right of [4957] data in right of [4978] data in right of [4987] data in right of [4993] find data is : [4996] ------------------------ data in right of [4999] data in left of [7498] data in left of [6247] data in left of [5623] data in left of [5311] data in left of [5155] data in left of [5077] data in left of [5038] data in left of [5017] data in left of [5008] data in left of [5002] not find data ...