#!/usr/bin/env python
#_*_ coding:utf-8 _*_
#encoding=utf-8
#function:实现二分法查找的方法
#created by xkq
#date: 2018
def BinarySearch_1(data_source,find):#方法一
mid = int(len(data_source) / 2)
if len(data_source)>1:
if data_source[mid]>find:
#print(data_source[:mid])
#print("on the left of %s"%data_source[mid])
BinarySearch_1(data_source[:mid],find)
elif data_source[mid]
#print(data_source[mid:])
#print("on the right of %s" % data_source[mid])
BinarySearch_1(data_source[mid:], find)
else:
print("find:%s"%data_source[mid])
elif len(data_source)==1:
if data_source[mid]==find:
print("find:%s" % data_source[mid])
else:
print("no find")
def BinarySearch(data_source,find):#方法二
low=0#列表起始位置
height=len(data_source)-1#列表结束位置
while low<=height:
mid=int((low+height)/2)#列表中间位置
if data_source[mid]
low=mid+1
elif data_source[mid]>find:
height=mid-1
else:
print( "find %s in list[%s]"%(data_source[mid],mid))#返回查找到的数和位置
return
else:
print("no find %s"%find)
if __name__=='__main__':
data=list(range(1,30000000,3))#创建数字列表
BinarySearch_1(data,91)#方法一调用
BinarySearch(data,91)#方法二调用