现在的位置: 首页 > 综合 > 正文

Python实现二分查找

2019年06月10日 ⁄ 综合 ⁄ 共 583字 ⁄ 字号 评论关闭

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

'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!')

抱歉!评论已关闭.