Binary Search implementation in Python

别说谁变了你拦得住时间么 提交于 2019-12-01 13:56:30
cs95

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

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