二分搜尋 (Binary Search) 是有序陣列查找的基石演算法,時間複雜度 O(log n)。雖然邏輯簡單,但邊界條件極易出錯。本文提供標準正確實作、常見錯誤分析、變體模式 (左邊界/右邊界/插入位置) 與 Python 內建工具應用。
def binary_search(arr: list, target: int) -> int:
"""
返回 target 在有序陣列 arr 中的索引,不存在返回 -1
前提:arr 嚴格遞增 (無重複) 或非遞減 (允許重複,返回任一匹配)
"""
left, right = 0, len(arr) - 1 # 閉區間 [left, right]
while left <= right: # 區間非空
mid = (left + right) // 2 # 或 left + (right - left) // 2 防溢位 (Python 無此問題)
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
| 錯誤代碼 | 問題 | 修正 |
|---|---|---|
| `while left < right:` | 漏檢 `left == right` 情況 | `while left <= right:` |
| `mid = (left + right) / 2` | Python 3 產生 float | `//` 整數除法 |
| `left = mid` / `right = mid` | 未排除 mid,可能死循環 | `left = mid + 1` / `right = mid - 1` |
| 未處理空陣列 | `right = -1` 導致索引錯誤 | 前置檢查 `if not arr: return -1` |
def lower_bound(arr: list, target: int) -> int:
"""返回第一個 >= target 的索引,若全小則返回 len(arr)"""
left, right = 0, len(arr) # 左閉右開 [left, right)
while left < right:
mid = (left + right) // 2
if arr[mid] < target:
left = mid + 1
else:
right = mid
return left # left == right
def upper_bound(arr: list, target: int) -> int:
"""返回第一個 > target 的索引,若全 ≤ target 則返回 len(arr)"""
left, right = 0, len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] <= target:
left = mid + 1
else:
right = mid
return left
def find_range(arr: list, target: int) -> tuple:
"""返回目標值出現的首尾索引 (含),不存在返回 (-1, -1)"""
first = lower_bound(arr, target)
if first == len(arr) or arr[first] != target:
return -1, -1
last = upper_bound(arr, target) - 1
return first, last
import bisect
arr = [1, 2, 2, 2, 3, 4, 5]
bisect.bisect_left(arr, 2) # => 1 (lower_bound)
bisect.bisect_right(arr, 2) # => 4 (upper_bound)
bisect.insort_left(arr, 2) # 插入保持有序 (左側)
bisect.insort_right(arr, 2) # 插入保持有序 (右側)
# 找區間
left = bisect.bisect_left(arr, 2)
right = bisect.bisect_right(arr, 2)
count = right - left # 出現次數 = 3
**生產環境優先使用 `bisect`** — C 實現、經過充分測試、支援任意序列類型。
def test_binary_search():
test_cases = [
([], 5, -1),
([1], 1, 0),
([1], 2, -1),
([1,2,3,4,5], 3, 2),
([1,2,3,4,5], 0, -1),
([1,2,3,4,5], 6, -1),
([1,2,2,2,3], 2, 1), # 返回任一匹配
(list(range(1000)), 500, 500),
]
for arr, target, expected in test_cases:
assert binary_search(arr, target) == expected
assert bisect.bisect_left(arr, target) == (expected if expected != -1 else len(arr))
# 邊界測試
assert lower_bound([1,2,3], 0) == 0
assert lower_bound([1,2,3], 4) == 3
assert upper_bound([1,2,3], 0) == 0
assert upper_bound([1,2,3], 3) == 3
assert upper_bound([1,2,3], 4) == 3
print("All tests passed!")
test_binary_search()