binary search in python weird behavior

烈酒焚心 提交于 2019-12-23 21:17:07

问题


Please look at this code:

def chop(array, search):
        lo = 0
        high = len(array) - 1
        while lo <= high:
                mid = (high + lo) /2
                if array[mid] == search:
                        return 'true'
                elif search > array[mid]:
                        low = mid + 1
                else:
                        high = mid - 1
        return 'false'



if __name__ == '__main__':
        a = [1,2,3,4,5,6,7,8,9,10]
        print chop(a, 3)

I wrote this little script which is supposed to search for number in array - regular binary search. So I run the script, and for example when I put in chop(a, 1) I get true, when I put in chop(a, 2) I get true, but when I put chop(a, 3) I don't get an answer, just empty line in the Python Shell.

Does anyone have an idea on what is going on?


回答1:


I'm guessing this is your bug:

low = mid + 1

Your while loop uses the variable lo, and you're defining a new variable called low within your while loop. In essence, you're never updating your lo variable.

Change that line to:

lo = mid + 1

and your algorithm should work.



来源:https://stackoverflow.com/questions/9918348/binary-search-in-python-weird-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!