1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| def binary_search(arr, target): """二分查找""" left, right = 0, 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
import pytest
class TestBinarySearch: def test_target_found(self): arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] assert binary_search(arr, 5) == 4 def test_target_not_found(self): arr = [1, 2, 3, 4, 5] assert binary_search(arr, 6) == -1 def test_empty_array(self): assert binary_search([], 1) == -1 def test_single_element(self): assert binary_search([1], 1) == 0 assert binary_search([1], 2) == -1 def test_duplicates(self): arr = [1, 2, 2, 2, 3] result = binary_search(arr, 2) assert result in [1, 2, 3]
|