python 二分法查找第k大_Python-二分法查找

#!/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)#方法二调用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值