0
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在数组中存在时起作用,但是当您要求它在给定元素之外查找值时,它不再起作用......

有谁知道为什么?

4

2 回答 2

0

来自http://docs.python.org/2/library/bisect.html

import bisect
bisect.bisect_left(li, targetValue)
于 2013-11-14T23:42:17.243 回答
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
于 2013-11-14T23:42:49.293 回答