二进制搜索算法 - Python

时间:2015-09-03 05:53:10

标签: python

在python中,在实现二进制搜索算法时,哪个数学函数最适合用于找出中间值 - floor或ceil?

3 个答案:

答案 0 :(得分:1)

您不需要使用ceil或floor函数在python中实现二进制搜索。根据问题,您必须向上或向下舍入中间值。

 mid = low + (high-low)/2 #rounds down the mid value
 mid = low + (high-low+1)/2 #rounds up the mid value

尝试解决这两个问题,您将了解其工作原理。

  1. 给定数组A和目标值,返回A中第一个元素的索引等于或大于目标值
  2. 给定数组A和目标值,返回小于目标值的最后一个元素的索引。
  3. 首先尝试自己解决这些问题,如果遇到问题,请参阅this.

答案 1 :(得分:0)

根据我对floorceil的理解,似乎没有更优化的选项。您可能希望在此网站中找到more

答案 2 :(得分:0)

你实际上不需要使用提到的ceil或者地板@shivam_mitra。 如果需要,这是一个二进制搜索算法。

 def bSearch(L, e, low, high):
    """ 
    L: is a sorted list
    e: is the targeted number 
    low: is the lowest value of the list
    hight: is the highest value of list
    """
    if len(L) == 0:                 # empty list
        return False 

     if high == low:                    # if the list is one element 
        return L[low] == e

     mid = low + int((high - low)/2)

     if L[mid] == e:                    # If the midpoint is the targeted number 
        return True
     if L[mid] > e:                     # check if the number is in the lower half of the list
        return bSearch(L, e, low, mid - 1)
     else:                              # otherwire it is in the higher of the list
        return bSearch(L, e, mid + 1, high)