def binary_search(li, targetValue):
low, high = 0, len(li)
while low <= high:
mid = (high - low)/2 + high
if li[mid] > targetValue:
low = mid - 1;
elif li[mid] < targetValue:
high = mid + 1;
elif li[mid] == targetValue:
return "we found it!"
print start, end
return False
我几乎肯定它有效。它在数组中存在targetValue
时有效,但是当你要求它在给定元素之外找到一个值时,它就不再起作用了......
有谁知道为什么?
答案 0 :(得分:0)
来自http://docs.python.org/2/library/bisect.html
import bisect
bisect.bisect_left(li, targetValue)
答案 1 :(得分:0)
我不确定你要打印的是什么,但是我看到那个功能可能存在一些不当行为。尝试这样的事情:
# binary search for list with desending values
def binary_search(li, targetValue):
low, high = 0, len(li) - 1 # min & max index
while low <= high: # loop til high & low switch
mid = (high + low) / 2 # midpoint (rounds down)
if li[mid] > targetValue: low = mid + 1 # confine to upper half
elif li[mid] < targetValue: high = mid - 1 # confine to lower half
elif li[mid] == targetValue: return mid # found it!
return None # nothing to return (low/high switched, so it wasn't found)
如果targetValue
位于li
,则会返回匹配的索引,否则返回None
。使用如下:
li = [10000, 1000, 100, 10, 1]
if binary_search(li, 500) is None: print '500 not found!'
else: print '500 found!'
i = binary_search(li, 10)
if i is None: print '10 not found!'
else: print 'Found 10 at index ' + str(i) + '!'
那会输出:
500 not found!
Found 10 at index 3!
对于加入li
,只需切换<
和>
:
def binary_search(li, targetValue):
low, high = 0, len(li) - 1
while low <= high:
mid = (high + low) / 2
if li[mid] < targetValue: low = mid + 1
elif li[mid] > targetValue: high = mid - 1
elif li[mid] == targetValue: return mid
return None