Binary Search implementation in Python

亡梦爱人 提交于 2019-12-01 12:29:35

问题


I am trying to implement a solution using binary search. I have a list of numbers

list = [1, 2, 3, 4, 6]
value to be searched = 2

I have written something like this

def searchBinary(list, sval):
    low = 0
    high = len(list)

    while low < high:
        mid = low + math.floor((high - low) / 2)

        if list[mid] == sval:
            print("found : ", sval)
        elif l2s[mid] > sval:
            high = mid - 1
        else:
            low = mid + 1

but when I am trying to implement this, I am getting an error like: index out of range. Please help in identifying the issue.


回答1:


A few things.

  1. Your naming is inconsistent. Also, do not use list as a variable name, you're shadowing the global builtin.

  2. The stopping condition is while low <= high. This is important.

  3. You do not break when you find a value. This will result in infinite recursion.


def searchBinary(l2s, sval): # do not use 'list' as a variable
    low = 0
    high = len(l2s) 

    while low <= high: # this is the main issue. As long as low is not greater than high, the while loop must run
        mid = (high + low) // 2

        if l2s[mid] == sval:
            print("found : ", sval)
            return
        elif l2s[mid] > sval:
            high = mid - 1
        else:
            low = mid + 1

And now,

list_ = [1, 2, 3, 4, 6]
searchBinary(list_, 2)

Output:

found :  2



回答2:


UPDATE high = len(lst) - 1 per comments below.


Three issues:

  1. You used l2s instead of list (the actual name of the parameter).
  2. Your while condition should be low <= high, not low < high.
  3. You should presumably return the index when the value is found, or None (or perhaps -1?) if it's not found.

A couple other small changes I made:

  • It's a bad idea to hide the built-in list. I renamed the parameter to lst, which is commonly used in Python in this situation.
  • mid = (low + high) // 2 is a simpler form of finding the midpoint.
  • Python convention is to use snake_case, not camelCase, so I renamed the function.

Fixed code:

def binary_search(lst, sval):
    low = 0
    high = len(lst) - 1

    while low <= high:
        mid = (low + high) // 2

        if lst[mid] == sval:
            return mid
        elif lst[mid] > sval:
            high = mid - 1
        else:
            low = mid + 1

    return None

print(binary_search([1, 2, 3, 4, 6], 2))  # 1


来源:https://stackoverflow.com/questions/45311232/binary-search-implementation-in-python

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