简体   繁体   中英

Binary Search counter

I create a list of len 100

li2 = list(range(100))

I use the below binary search function, with a counter, however it takes 5 searches to find 50. Should find it on the first try. (100/2) = 50 li2[50] == 50

def binary_search(li,item):
    low = 0
    high = len(li)-1
    trys = 0 
    while low<=high:
        mid = int((low + high)/2)
        guess = li[mid]
        if guess == item:
            return'Found',item, 'in', trys,'searches'
        elif guess > item:
            trys+=1
            high = mid - 1
        else:
            trys+=1
            low = mid + 1
    return item,' not found', trys, ' searches attempted'

I run binary_search(li2,50)

and returns below

('Found', 50, 'in', 5, 'searches')

range(100)将返回一个列表,其中包含从0到99的所有元素。您的二进制搜索算法将开始在49而不是50上搜索。

Why reinventing the wheel when you can use bisect , which often have a native implementation, so it's very fast.

bisect_left returns the insertion position of the current item in the list (which must be sorted of course). If the index is outside list range, then item is not in list. If index is within list range and item is located at this index, then you've found it:

import bisect

def binary_search(li,item):
    insertion_index = bisect.bisect_left(li,item)
    return insertion_index<len(li) and li[insertion_index]==item

testing:

li2 = list(range(100))
print(binary_search(li2,50))
print(binary_search(li2,-2))
print(binary_search(li2,104))

results:

True
False
False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM