二进制搜索不返回值

ie3xauqp  于 2021-09-29  发布在  Java
关注(0)|答案(3)|浏览(302)

函数没有返回任何内容我不知道为什么,但程序会无限期运行

def binary_search(li,key):
    li.sort()
    #setting indexes
    low = 0
    high = len(li)-1 # becuse we know len is every item in the list
    while low <= high: # setting midpoint
        midpoint = (low-high)//2 # two divide sign makes return of operation interger not float
        if li[midpoint] == key:
            print('key found')
            return midpoint
        elif li[midpoint] < key:
            low = midpoint+1
        else:
            high = midpoint-1
    return -1

# always return -1 if key not found

li = [1,2, 3, 4, 5, 6 , 7, 8]
print(binary_search(li, 7))
roqulrg3

roqulrg31#

这个 midpoint 是介于 lowhigh . 要获得它,您需要使用 midpoint = (low + high) // 2 而不是这个(这就是代码无限期运行的原因) midpoint = (low - high) // 2

0ve6wy6x

0ve6wy6x2#

试试这个

def binary_search(li, key):
    li.sort()
    low = 0
    high = len(li)-1 
    while low <= high:
        midpoint = (low+high)//2
        if li[midpoint] == key:
            print('key found')
            return midpoint
        elif li[midpoint] < key:
            low = midpoint+1
        else:
            high = midpoint-1
    return -1

li=[1,2, 3, 4, 5, 6 , 7, 8]
print(binary_search(li, 7))
xzlaal3s

xzlaal3s3#

下面是这个简单的二进制搜索的解决方案。
def搜索(li,键):

将索引设置为低=0

high=len(li)-1因为我们知道len是列表中的每一项
低时<=高时:#设置中点

midpoint = (low+high)//2#two divide sign makes return of operation interger not float

  if li[midpoint] == key:

      print('key found')

      return midpoint

  elif li[midpoint] < key:

      low = midpoint+1

  else:

      high = midpoint  # it should be midpoint not midpoint-1

返回-1

如果找不到键,请始终返回-1 li=[1,2,3,4,5,6,7,8]

打印(搜索(li,5))

相关问题