Python-二分法查找
2018-06-18 02:20:52来源:未知 阅读 ()
#!/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]<find:
#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]<find:
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)#方法二调用
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:pip显示网络不可达错误解决
下一篇:python之文件操作
- Python-19-元类 2019-07-24
- Python-17-反射 2019-07-24
- Python-16-继承、封装、多态 2019-07-24
- Python-18-类的内置属性 2019-07-24
- Python-15-面向对象 2019-07-24
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
