Python 实现二分查找

二分查找:


  #操作对象只能是顺序表,最优时间复杂度:O(1),最坏时间复杂度:O(logn)


  #二分查找,递归
  def binary_search(list,item):

    n = len(list)
    if n > 0:
      mid = n // 2
      if list[mid] == item:
        return True
      elif item < list[mid]:
        return binary_search(list[:mid],item)
      else :
        return binary_search(list[mid+1:],item)
    return False

 

  #二分查找,非递归
  def binary_search2(list,item):
    n = len(list)
    first = 0
    last = n - 1
    while first <= last:
      mid = (first + last)//2
      if list[mid] == item:
        return True
      elif item < list[mid]:
        last = mid - 1
      else:
        first = mid + 1
    return False

 

posted @ 2018-07-26 09:59  大伦  阅读(167)  评论(0编辑  收藏  举报