Python实现二分查找


Python #二分查找 #算法2012-11-20 10:00

代码如下:

'fileName--BinarySearch.py'

src = []

def BinarySearch(low, high, target, *src):
    '二分查找 http://yige.org '
    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!')


相关文章

粤ICP备11097351号-1