Python 二分法查找

1.如果找到该值就返回

2.如果找不到该值就返回该值的上一个Index和下一个Index

3.小于List[0] 返回0

4.大于len(List)返回该List[-1]


def BinarySearch(keyTime,List):
    low = 0
    high = len(List) - 1
    middle = 0
    
    while(low <= high):
        middle = int((low + high) / 2)
        #获取中间数据
        listTime = List[middle][0]
        if listTime == keyTime:
            return listTime
            break
        elif listTime < keyTime:
            low = middle + 1
        elif listTime > keyTime:
            high = middle - 1
        
        if high < 0:
            print '不在List范围内'
            return 0
        elif low > len(List) - 1:
            print '超出List范围'
            return len(List)
        else:
            return (high,low)


你可能感兴趣的:(list,python)