共計 453 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
以下是一個簡單的二分查找算法的 Python 代碼實現(xiàn):
def binary_search(arr, target):
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
使用該算法時,需要傳入一個有序的數(shù)組 arr
和要查找的目標值 target
。函數(shù)會返回目標值在數(shù)組中的索引,如果目標值不在數(shù)組中,則返回 -1。
以下是一個使用示例:
arr = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
target = 23
result = binary_search(arr, target)
if result != -1:
print(f" 目標值 {target} 在數(shù)組中的索引為 {result}")
else:
print(" 目標值不在數(shù)組中 ")
輸出:
目標值 23 在數(shù)組中的索引為 5
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完