您的位置:首页 > 编程语言 > Python开发

Python实现二分查找

2015-04-03 11:08 489 查看
http://blog.csdn.net/vipygd/article/details/7555759

这么晚,没事干,写个程序练练手,最近在看Python,就拿Python开刀吧;上oschina看有人写了个二分查找的东西,看了下有问题,所以自己忍不住也拿出来写写;纯练手!!!

[python] view
plaincopyprint?

'fileName--BinarySearch.py'



src = []



def BinarySearch(low, high, target, *src):

'二分查找'

while low <= high:

mid = (low + high) // 2

midVal = src[mid]

if target < midVal:

high = mid - 1

elif target > midVal:

low = mid + 1

else:

return mid

BinarySearch(low, high, target, *src)



print('Please input 10 number:')

for number in range(10):

src.append(int(input('Num %d:' % number)))



sortList = tuple(src)



key = int(input('Please input key:'))

location = BinarySearch(0, len(src) - 1, key, *sortList)



if location != None:

print('Find target at %d' % (location + 1))

else:

print('No target!')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: