简体   繁体   English

如何修复递归代码,使其具有与迭代版本相同的渐近运行时间(但仍然是递归的)

[英]How to fix the recursive codeso that it has the same asymptotic running time as the iterative version (but is still recursive)

I was struggling to figure out what changes need to be made to the recursive version of my code below so that the asymptotic run time just about matches the iterative version.我一直在努力弄清楚需要对下面代码的递归版本进行哪些更改,以便渐近运行时间与迭代版本相匹配。 Of course, the recursive version of the code still needs to be recursive, but I was stuck on how I should approach cutting down the run time on the recursion.当然,代码的递归版本仍然需要递归,但我一直在思考应该如何减少递归的运行时间。

def binarySearch(alist, item): //ITERATIVE VERSION
    first = 0
    last = len(alist)-1
    found = False
    while first<=last and not found:
        midpoint = (first + last)/2
        if alist[midpoint] == item:
            found = True
        else:
            if item < alist[midpoint]:
                last = midpoint-1
            else:
                first = midpoint+1
    return found

def binarySearch(alist, item): //RECURSIVE VERSION
    if len(alist) == 0:
        return False
    else:
        midpoint = len(alist)/2
        if alist[midpoint]==item:
            return True
        else:
            if item<alist[midpoint]:
                return binarySearch(alist[:midpoint],item)
            else:
                return binarySearch(alist[midpoint+1:],item)

Tried to replicate my function recursively, but the asymptotic running time was much slower than the iterative version.试图递归复制我的 function,但渐近运行时间比迭代版本慢得多。

Your recursive version creates new lists -- which is detrimental to both time and space complexity.您的递归版本会创建新列表——这对时间和空间复杂性都是不利的。

So instead of slicing alist , use first and last like you did in the iterative version:因此,不要切片alist ,而是像在迭代版本中那样使用firstlast

def binarySearch(alist, item, first=0, last=None):
    if last is None:
        last = len(alist) - 1
    if last < first:
        return False
    else:
        midpoint = (start + end) // 2
        if alist[midpoint] == item:
            return True
        elif item < alist[midpoint]:
            return binarySearch(alist, item, first, midpoint - 1)
        else:
            return binarySearch(alist, item, midpoint + 1, last)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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