约翰·古塔格(John Guttag)手指练习第10章

时间:2019-02-01 22:25:04

标签: python-3.x recursion binary

这个代码是从Guttag的介绍节目。 10.3节的手指运动:

def search(L, e):
    """Assumes L is a list, the elements of which are in
     ascending order.
     Returns True if e is in L and False otherwise"""

     def bSearch(L, e, low, high):
         #Decrements high - low
         if high == low:
             return L[low] == e
         mid = (low + high)//2
         if L[mid] == e:
             return True
         elif L[mid] > e:
             if low == mid: #nothing left to search
                 return False
              else:
                 return bSearch(L, e, low, mid - 1)
         else:
             return bSearch(L, e, mid + 1, high)

     if len(L) == 0:
         return False
     else:
         return bSearch(L, e, 0, len(L) - 1)

我没有把头放在递归上。为什么在第二次 nd 递归调用中使用mid+1而不是mid

1 个答案:

答案 0 :(得分:0)

这是一个二进制搜索,因此在每次递归时,您都会将列表分成两半。如果您要进行递归调用,您已经检查了mid处的元素,而这并不是您要查找的(如果已经找到,您将返回{{1 }},并且无需重复执行)。因此,您选择一个搜索方向(搜索列表的一半),然后递归搜索该一半。但是,无论选择哪一半,您都已经知道true索引中的元素不是您要查找的元素,因此您无需再次检查它,因此您无需将其包含在您重复出现的列表中。