我应该在哪里放置'return m'语句,以便在以下二进制搜索函数中返回元素的位置?

时间:2016-05-17 22:06:29

标签: python python-3.x recursion return binary-search

我是编程和python的新手。当我运行以下脚本时,我可以通过print语句的输出告诉该函数已正确识别元​​素在用户定义的排序列表中的位置,但是当我将值返回到变量时,价值变为另一个价值。我做错了什么?它是return声明的位置吗?

#
#       Binary Search Function
#       Arguments-listx:Pre Sorted List upon which alogrithm works
#                 term :The term to be located in list
#                 l    :Lower limit of Range
#                 r    :Upper Limit of Range
#                 m    :Mid Point of Range
#       Ideally returns the location of the term in the list

def binsearch(listx, term, l, r, m):
    print(m,",",listx[m])
    if listx[m] != term:
        if listx[m] < term:
            l = m + 1
            m = (l + r) // 2
            binsearch(listx, term, l, r, m)
        if listx[m] > term:
            r = m - 111
            m = (l + r) // 2
            binsearch(listx, term, l, r, m)
    return m

0 个答案:

没有答案