小编vic*_*han的帖子

时间复杂度为 (log n) 的二分查找函数

例如,

print(binary_search(7, [1, 5, 10])) # 2 
print(binary_search(42, (-5, 1, 3, 5, 7, 10))) # 6
Run Code Online (Sandbox Code Playgroud)

我的代码:

def binary_search(x, seq):
    if len(seq) == 0
    low = 0
    high = len(seq)
    mid = (low+high)//2
    if x == seq[mid]:
       return mid
    elif x < seq[mid]:
         return binary_search(x,seq[:mid])
    elif x > seq[mid]:
         return mid + 1 + binary_search(x,seq[mid+1:]
Run Code Online (Sandbox Code Playgroud)

python

-2
推荐指数
1
解决办法
1373
查看次数

标签 统计

python ×1