【问题标题】:Index error in binary search in an infinite sorted array无限排序数组中的二进制搜索中的索引错误
【发布时间】:2021-12-27 05:40:44
【问题描述】:

当元素不存在或太大时,程序在无限排序数组中的二分查找中给出IndexError: list index out of range

def binarySearch(l,ele,low=0,high=None):
    if(high==None):
        high=len(l)-1
    if(low>high):
        return -1
    mid= int((low+high)/2)
    pEle = l[mid]
    if(pEle==ele):
            return mid 
    elif(pEle>ele):
        return binarySearch(l,ele,low,mid-1)
    else:
        return binarySearch(l,ele,mid+1,high)
# This is a function that searches elements in an infinite sorted array
# l=array;ele=element
def binarySearchInfiniteSortedArray(l,ele):
    low,high=0,1
    while(True):
        pEle = l[high]
        if(pEle==ele):
            return high
        elif(pEle>ele or pEle==l[-1]):
            break
        else:
            low,high = high+1,high*2
    return binarySearch(l,ele,low,high)

【问题讨论】:

  • 您可以尝试使用算术平均值进入该范围,但几何平均值会让您更快地得到答案。

标签: python arrays algorithm binary-search index-error


【解决方案1】:

high 的值在每个循环中都翻倍,当high 的值大于或等于列表长度时,它会给出IndexError: list index out of range

def binarySearchInfiniteSortedArray(l,ele):
    low,high=0,1
    while(True):
        try:
            pEle = l[high]
        except:
            high = int((high**0.5)*(low**0.5))
            continue
        if(pEle==ele):
            return high
        elif(pEle>ele or pEle==l[-1]):
            break
        else:
            low,high = high+1,high*2
    return binarySearch(l,ele,low,high)

一旦出现错误,我们可以试一试,除非你再次在范围内或得到答案,否则得到 highlow 的几何平均值。希望我的观点很清楚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    相关资源
    最近更新 更多